【发布时间】:2012-01-02 09:53:40
【问题描述】:
我正在实现一个单例模式。在这里,我正在 GetInstance 中创建一个 Singleton* 的新实例,当我尝试在析构函数中删除它时,它会无限循环。在这种情况下如何避免内存泄漏?
请参考以下代码:
#define NULL 0
class Singleton
{
private :
static Singleton* m_pInstance;
Singleton(){};
public :
static Singleton* GetInstance()
{
if(m_pInstance == NULL)
{
m_pInstance = new Singleton();
}
return m_pInstance;
}
~Singleton()
{
//delete m_pInstance; // The system goes in infinate loop here if i uncomment this
m_pInstance = NULL;
}
};
Singleton* Singleton ::m_pInstance = NULL;
int main()
{
Singleton* pInstance = Singleton::GetInstance();
delete pInstance;
}
【问题讨论】:
-
我在一个单线程应用程序中
-
为什么要销毁单例?静态分配。
-
单例中的全部要点是您不能删除它。它应该代表一个始终可访问的对象。如果不是,那么它当然不应该是单例
-
@Atul 你为什么要定义
NULL 0?语言已经提供了这一点。顺便说一句,如果你的编译器支持 C++11,你应该改用nullptr。 -
@jalf "它应该代表一个始终可以访问的对象。如果不是,那么它肯定不应该是一个单例"......对不起,我请求推迟.这根本不是单例的“全部要点”。最多可能是副作用。顾名思义,单例的意义在于防止您的应用程序创建该类的多个对象