gpt4 book ai didi

c++ - 单例内存什么时候删除?

转载 作者:行者123 更新时间:2023-11-28 00:20:54 25 4
gpt4 key购买 nike

我见过标准的(大多数人使用这个)单例设计模式,但在这里我对何时删除内存感到困惑。

我们是否必须明确地编写静态 delete() 函数并在最后删除内存?

class ST
{
static ST* instance;
ST(){};

private :

static ST* getInstance();

};


ST* ST::instance = NULL;
ST* ST::getInstance()
{
//lock on mutex
if(NULL == instance)
{
instance = new ST();
}

return instance;
}

最佳答案

是的,内存不会自动释放。可能,如果你想释放单例内存,在这种情况下最好的方法是调用 atexit具有功能,可以释放单例。如果您使用 C++11,最好的方法是使用 Meyers 单例。

ST& ST::getInstance()
{
static ST instance;
return instance;
}

关于c++ - 单例内存什么时候删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27565021/

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