'Resource Acquisition Is Initialization' for solving memory leak issue

93 Views Asked by At

I am trying to optimize part of code for a project. There are some context to show:

Class Basic
{
  type* _shareResource;
  virtual Basic(){};
  virtual ~Basic(){};
  virtual void initialResource() = 0;
  virtual void deleteResource() = 0;
  virtual void ownmethod() = 0;
  static Basic* createChild(int condition);
}
Basic* Basic::createChild(int condtion)
{
   Basic* pointer;
   if (condition ==  1)
       pointer = new ChildA();
   else 
       pointer = new ChildB();  
   return pointer; 
}


Class ChildA::public Basic
{
  void initialResource(){ allocate memory for _shareResource;}
  void deleteResource(){ delete _shareResource; _shareResource = NULL;}
  ChildA(){ initialResource(); }
  ~ChildA(){ deleteResource(); }
  virtual ownmethod() {// child A method}

}

Class ChildB::public ChildA
{
  void initialResource(){ allocate memory for _shareResource;}
  void deleteResource(){ delete _shareResource; _shareResource = NULL;}
  ChildB(){ initialResource(); }
  ~ChildB(){ deleteResource(); }
  virtual ownmethod(){// child B method}
}

so, when I use Basic::createChild() as a client: Basic* aPointer = CreateChild(1); //after some usage, the client should delete this ponter delete aPointer;

However RALL require Basic delete itself without help from client. So I am trying to modify the code. What I did is:

boost::share_ptr<Basic> Basic::createChild(int condtion)
{
   boost::share_ptr<Basic> pointer;
   if (condition ==  1)
       pointer = boost::share_ptr<ChildA>(new ChildA());
   else 
       pointer = boost::share_ptr<ChildA>(new ChildB());
   return pointer   
}

But I got core dump as memory leak, I checked it from deleteResource() of child class, but I don't know why.

Could you help me to explain the core dump or provide a better solution for following RALL principle? Thanks a lot. (I prefer to keep createChild as static method, since my optimization should not modify too much client code)

2

There are 2 best solutions below

3
On

Declare the destructor of Basic virtual. It's likely the derived classes destructors are not being called.

0
On

Why so complicated !?

class Shared
{
   protected:
   struct Implementation
   {
       virtual ~Implementation() {}
   };

   protected:
   Shared(Implementation* p)
   : m_self(p)
   {}

   private:
   std/boost::shared_ptr<Implementation> m_self;
}

And have derived classes with a nested class derived from Shared::Implementation

However, passing a std/boost::shared_ptr< SomeClass > would do it, too