Are there any issues with allocating memory within constructor initialization lists?

前端 未结 7 919
后悔当初
后悔当初 2020-12-05 10:50

I have used initialization lists a great deal in my C++ programs but wasn\'t aware that you could allocate memory within them.

So you can do something (as a contrive

7条回答
  •  星月不相逢
    2020-12-05 11:08

    There's no specific issue with calling new from the initializer list.

    However, if you do it for multiple members, it won't be exception-safe, and you risk leaking memory (what if the first new call succeeds, but the second throws an exception? Then the first allocation is leaked).

    As for relying on the initialization order, that's perfectly safe. Members are initialized in the order in which they're listed in the class declaration. So you can use the value of members initialized early, to initialize "later" members.

    Just keep in mind that it's their declaration order inside the class, and not their order in the initialization list that determines their initialization order. :)

提交回复
热议问题