C++ idiom to avoid memory leaks?

后端 未结 11 1605
被撕碎了的回忆
被撕碎了的回忆 2021-01-28 21:01

In the following code, there is a memory leak if Info::addPart1() is called multiple times by accident:

typedef struct
{
}part1;

typedef struct
{
}         


        
11条回答
  •  再見小時候
    2021-01-28 21:19

    I agree with the group that you should use some kind of smart pointer.

    If you do decide to continue with bare pointers, be aware that your class above does not have a copy constructor defined by you. Therefore, the C++ compiler has defined one for you that will just do a simple copy of all the pointers; which will lead to a double delete. You'll need to define your own copy constructor (or at least create a stub private copy constructor if you don't think you need a copy constructor).

    Info(const Info &rhs)
    {
      _ptr1 = new part1[rhs._ptr1];
      _ptr2 = new part2[rhs._ptr2];
    }
    

    You will have a similar problem with the default assignment operator.

    If you choose the correct smart pointer, these problems will go away. :)

提交回复
热议问题