我有以下代码:
我的类.h:
static MyMutex instanceMutex;
static MyClass* getInstance();
static void deleteInstance();
我的类.c:
MyMutex MyClass::instanceMutex;
MyClass* MyClass::getInstance()
{
if (theInstance == 0)
{
instanceMutex.acquire();
if (theInstance == 0)
{
theInstance = new MyClass();
}
instanceMutex.release();
}
return theInstance;
}
void MyClass::deleteInstance()
{
if (theInstance != 0)
{
instanceMutex.acquire();
if (theInstance != 0)
{
theInstance->finalize();
delete theInstance;
theInstance = 0;
}
instanceMutex.release();
}
return;
}
我有两个问题:
- 以上代码是否正确安全?
在 MyClass::deleteInstance() 中调用“delete theInstance”后,我调用
- 实例 = 0;
- instanceMutex.release();
但如果实例被删除,那怎么可能呢?类的内存是不是没有了?
最佳答案
如果它是一个单例 - 它被定义为只有一个实例 - 如果你删除它 - 它会下降到 0
看来你根本不应该支持删除
关于c++ - 正确删除单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20106516/