我对这段代码有一些疑问>任何讨论都会对理解这些事情很有帮助:
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;
}
在这个块中,我们正在删除“Singleton::destroy()”中的内存;
{
Singleton *sc1 = Singleton::getInstance();
sc1->method();
Singleton::destroy();
cout << sc1;
}
那么如何调用“sc2->method();” 成功了吗??
德韦什