gpt4 book ai didi

c++ - 为什么这个单例类代码工作正常?

转载 作者:行者123 更新时间:2023-11-28 00:39:13 24 4
gpt4 key购买 nike

<分区>

我对这段代码有一些疑问>任何讨论都会对理解这些东西很有帮助:

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;
}

在这个 block 中,我们正在删除“Singleton::destroy()”中的内存;

{
Singleton *sc1 = Singleton::getInstance();
sc1->method();
Singleton::destroy();
cout << sc1;
}

那么这怎么调用“sc2->method();”成功了吗??

开发

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com