【发布时间】:2017-04-19 19:44:10
【问题描述】:
所以我写了一个简单的单例类。当我创建一个对象时,会调用构造函数,但它的析构函数(释放对象)似乎在超出范围时不会被调用。
#include <iostream>
using namespace std;
class Singleton {
public:
static Singleton &getInstance( )
{
if (instance == nullptr) {
cout << "Creating instance.\n";
instance = new Singleton();
}
return *instance;
}
static void destroyInstance( )
{
if (instance != nullptr) {
cout << "Destroying instance.\n";
delete instance;
instance = nullptr;
}
}
~Singleton( )
{
if (instance != nullptr) {
cout << "Destroying instance.\n";
delete instance;
instance = nullptr;
}
}
private:
Singleton( ) { }
static Singleton *instance;
};
Singleton *Singleton::instance = nullptr;
int main( )
{
Singleton &singleton = Singleton::getInstance();
//singleton.destroyInstance();
return 0;
}
使用析构函数代码,程序只输出这个。
Creating instance.
如果我注释掉析构函数并使用destroyInstance() 函数,它会输出这个。
Creating instance.
Destorying instance.
为什么要这样做?
编辑:我是个白痴。只是忽略了一堆东西。这个问题也可能被删除,因为它并不是那么有用。
【问题讨论】:
-
我很困惑。如果您不调用
delete,您希望什么机制对您的单身人士delete起作用?实现析构函数只是描述了当一个实例被销毁时会发生什么,它对 if 或 when 它被销毁没有任何影响。 -
你的析构函数至少会失败一次。
-
指针超出范围时不会被删除。通常一个单例会被初始化一次。在自己的析构函数中调用
delete也可能是一个非常糟糕的主意。 -
@FrançoisAndrieux 我真的不知道。据我了解,删除使用
new分配的内容只是一个好习惯。虽然我仍然会将析构函数用于其他事情。 -
@TomSmale 所以我写了一个简单的单例类——不像Meyer's singleton那么简单
标签: c++