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; }
And deletion of singleton class object would be allow only when the count is zero. To design C++ delete singleton instance, first, we need to make the singleton class destructor private, so, it can not be accessed from outside of the class. Hence, user cannot delete the singleton instance using the keyword “delete”.
Getting rid of a singleton is extremely easy: create an abstraction and depend on that instead of the concrete Singleton. Once this is done, you'll have to decide if you want to fix all the callers of your class or if you only want to do this locally because you don't have time for that or there are to many callers.
The beauty of the Meyers Singleton in C++11 is that it's automatically thread-safe. That is guaranteed by the standard: Static variables with block scope. The Meyers Singleton is a static variable with block scope, so we are done. It's still left to rewrite the program for four threads.
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 resources 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 !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With