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

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

    You are allocating memory in your initialiser-list; this is totally fine, but you are then assigning the pointers to that memory to raw pointers.

    These raw pointers do not imply any sort of memory ownership or deletion of the pointers that they point to, and as a result, the code contains several memory leaks, does not follow the "Rule of Five", and is generally bad.

    A far better way to write Test would be:

    class Test
    {
    private:
        //Assuming you actually want dynamic memory allocation:
        std::unique_ptr i;
        std::unique_ptr j;
        int count;
        std::unique_ptr k;
    
    public:
        Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
        {
        }
    };
    

提交回复
热议问题