C++ idiom to avoid memory leaks?

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

    Use construction is initialization instead.

    class Info
    {
        private:
        part1* _ptr1;
        part2* _ptr2;    
    
        public:
        Info() : _ptr1(new part1), _ptr2(new part2)
        {
        }
    
        ~Info()
        {
          delete _ptr1; 
          delete _ptr2;
        }
    };
    

    But in this case you might as well create the parts on the stack, so no new and delete is required.

    class Info
    {
        private:
        part1 _part1;
        part2 _part2;    
    
        public:
        Info()
        {
        }
    
        ~Info()
        {
        }
    };
    

    But I guess you want the pointers to be lazy created, then I wouldn't suggest to create public class methods that takes care of the initializations. This should be handled internally in the class, when the class need to allocate them.

提交回复
热议问题