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

前端 未结 7 920
后悔当初
后悔当初 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:15

    Suppose that you have:

    class Foo
    {
    public:
        T* p1;
        T* p2;
    
        Foo()
        : p1(new T),
          p2(new T)
        {
        }
    };
    

    If initializing p2 fails (either because new throws an out of memory exception or because the T constructor fails), then p1 will be leaked. To combat this, C++ allows using try/catch in initialization lists, but it's usually pretty gross.

提交回复
热议问题