C++ idiom to avoid memory leaks?

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

    Option 1: Use Java :)

    Option 2: Use auto_ptr

    std::auto_ptr _ptr1;
    std::auto_ptr _ptr2;
    
    public:
    addPart1()
    {
       _ptr1 = auto_ptr(new part1);
    }
    
    ...
    
    // no destructor is needed
    

提交回复
热议问题