Atul Atul - 2 months ago 9
C++ Question

How to delete Singleton pointer?

I was implementing a singleton pattern.Here,I am creating a new instance of Singleton* in GetInstance, when I try and delete it in the destructor, it does in infinite loop. How to avoid memory leak in this case ?

Please refer the below piece of code:

#define NULL 0
class Singleton
{
private :
static Singleton* m_pInstance;
Singleton(){};

public :

static Singleton* GetInstance()
{
if(m_pInstance == NULL)
{
m_pInstance = new Singleton();
}
return m_pInstance;
}

~Singleton()
{
//delete m_pInstance; // The system goes in infinate loop here if i uncomment this
m_pInstance = NULL;
}
};

Singleton* Singleton ::m_pInstance = NULL;

int main()
{
Singleton* pInstance = Singleton::GetInstance();
delete pInstance;
}

Answer

Of course it causes an infinite loop !

You call the destructor, but the destructor also calls the destructor, so the destructor calls the destructor again... and again...

If you want to use delete, you must use it from outside of the destructor and NOT call it again in the destructor.

To do that, you can use another static method which will mirror the GetInstance() method :

class Singleton  
{ 
public :

   ...

   // this method is a mirror of GetInstance
   static void ResetInstance()
   {
      delete m_pInstance; // REM : it works even if the pointer is NULL (does nothing then)
      m_pInstance = NULL; // so GetInstance will still work.
   }

   ...

   ~Singleton()
   { 
       // do destructor stuff : free allocated ressources if any.
       ...
   }

Note : the other people warn you about using a singleton and they are right because this pattern is often misused. So think before using it. But go ahead anyway, that is the good way to learn !

Comments