C++ idiom to avoid memory leaks?

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

    0 讨论(0)
  • 2021-01-28 21:35

    On the far extreme of possible ways to deal with memory leaks is the boehm garbage collector, a conservative mark & sweep collector. Interestingly, this can be used in addition to all the good advice offered in other answers.

    0 讨论(0)
  • 2021-01-28 21:37

    You should take a look at RAII

    0 讨论(0)
  • 2021-01-28 21:38

    Use a smart pointer such as boost:shared_ptr , boost:scoped_ptr is recommended to manage the raw pointer. auto_ptr is tricky to work with, you need pay attention to that.

    0 讨论(0)
  • 2021-01-28 21:38

    Option 1: Use Java :)

    Option 2: Use auto_ptr

    std::auto_ptr<part1> _ptr1;
    std::auto_ptr<part2> _ptr2;
    
    public:
    addPart1()
    {
       _ptr1 = auto_ptr<part1>(new part1);
    }
    
    ...
    
    // no destructor is needed
    
    0 讨论(0)
提交回复
热议问题