C++ idiom to avoid memory leaks?

后端 未结 11 1779
被撕碎了的回忆
被撕碎了的回忆 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:33

    Checking for nonzero pointer before delete is redundant. delete 0 is guaranteed to be a no-op.

    A common way to handle this is

    delete _ptr1;
    _ptr1 = 0;
    _ptr1 = new part1;
    

    Zeroing the pointer ensures there won't be any dangling pointers for example in the case part1 construction throws an exception.

提交回复
热议问题