i have a singleton class. I am creating an object of it. Using it. Once it will go out of scope destructor will be called.
Again creating anew object, since instanceFlag is false, it will again allocate new memory.
#include <iostream>
using namespace std;
class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
//private constructor
}
public:
static Singleton* getInstance()
{
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{
return single;
}
}
void method()
{
cout << "Method of the singleton class" << endl;
}
~Singleton()
{
instanceFlag = false;
}
};
bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
int main()
{
Singleton *sc1,*sc2;
{
sc1 = Singleton::getInstance();
sc1->method();
delete sc1;
}
sc2 = Singleton::getInstance();
sc2->method();
return 0;
}
My doubt is what will happen to old memory? I think its a memory leak. If yes how to fix this issue in the given code?
Any comments will be helpful to understand the internals.