C++ idiom to avoid memory leaks?

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

    Your suggested fix will work (though of course you're still at risk for a memory leak if addPart2() is called twice). A much safer approach is to use scoped_ptr from the Boost library collection (www.boost.org), which is a container that acts like a pointer, but guarantees that its target is deleted when the container is destroyed. Your revised class would then look like

    class Info
    {
        private:
        boost::scoped_ptr _ptr1;
        boost::scoped_ptr _ptr2;    
    
        public:
        Info() {}  // scoped_ptrs default to null
    
        // You no longer need an explicit destructor- the implicit destructor
        // works because the scoped_ptr destructor handles deletion
    
        addPart1()
        {
          _ptr1.reset(new part1);
        }
    
        addPart2()
        {
          _ptr2.reset(new part2);         
        }   
    };
    

    As a general principle, it's a good idea to avoid writing code that requires you to explicitly delete pointers. Instead, try to use containers that do it automatically at the appropriate time. Boost is a good resource for this kind of thing.

    All this assumes you have a reason ptr1_ and ptr2_ need to be pointers. If not, it's much better to make them ordinary objects; then you get memory management for free.

提交回复
热议问题