C++ idiom to avoid memory leaks?

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

    If you want it to have a lazy behavior you might consider this:

    addPart1()
    {
        if(_ptr1 == NULL) {
            _ptr1 = new part1;
        }
    }
    

    The way you suggested is also an alternative depending how you want it to behave. But other people have suggested better ways to do it, but as we really don't know why you made it this way and how the surrounding code works ...

提交回复
热议问题