I have some doubts in this code> Any discussion will be very helpful to understand the things:
class Singleton
{
private:
static Singleton *single;
Singleton() {}
~Singleton() {}
public:
static Singleton* getInstance()
{
if (!single)
single = new Singleton();
return single;
}
void method()
{
cout << "Method of the singleton class" << endl;
}
static void destroy()
{
delete single;
single = NULL;
}
};
Singleton* Singleton::single = NULL;
int main()
{
Singleton *sc2;
sc2 = Singleton::getInstance(); // sc2 is pointing to some memory location
{
Singleton *sc1 = Singleton::getInstance(); // sc1 and sc2 pointing to same memory location
sc1->method();
Singleton::destroy(); // memory location deleted.
cout << sc1;
}
sc2->method(); // ??? how this is working fine??
return 0;
}
inside this block, we are deleting the memory in "Singleton::destroy()";
{
Singleton *sc1 = Singleton::getInstance();
sc1->method();
Singleton::destroy();
cout << sc1;
}
Then how this call "sc2->method();" is successful??
Devesh