我有以下代码:
MyClass.h:
static MyMutex instanceMutex;
static MyClass* getInstance();
static void deleteInstance();
MyClass.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;
}
我对此有2个问题:
但是,如果删除该实例,那怎么可能呢?类里面的记忆没有了吗?
最佳答案
如果是单例-定义为只有一个实例-如果删除它-则降为0
所以看来您根本不应该支持删除
关于c++ - 正确删除单例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20106516/