【发布时间】:2015-06-02 18:21:59
【问题描述】:
几分钟前,我向question 询问了关于单例实现的问题,@LightnessRacesinOrbit 给出了很好的回答。
但我不明白为什么在下一个示例中,如果我在变量 inst 中实例化 Singleton,它的析构函数被调用了两次?
#include <iostream>
class Singleton
{
public:
~Singleton() { std::cout << "destruction!\n"; }
static Singleton& getInstance()
{
static Singleton instance;
return instance;
}
void foo() { std::cout << "foo!\n"; }
private:
Singleton() { std::cout << "construction!\n"; }
};
int main()
{
Singleton inst = Singleton::getInstance();
inst.foo();
}
输出:
construction!
foo!
destruction!
destruction!
更正确地说,我理解为什么它被调用了两次。但是我无法理解如何如果在第一次析构函数之后类的实例被销毁,它可以被调用两次?为什么没有例外?
或者它没有被摧毁?为什么?
【问题讨论】:
-
将
Singleton(Singleton const&) { std::cout << "copy construction!\n"; }添加到您的示例中,所有内容都会显示出来。 -
你应该使类不可复制和不可移动:
Singleton(Singleton const&) = delete; Singleton(Singleton &&) = delete; Singleton &operator=(Singleton const&) = delete;Singleton operator=(Singleton &&) = delete; -
您的程序中有 两个
Singleton类型的实例。一个是static在getInstance内。另一个是本地内部main。每个对象最终都会被销毁。因此有两个析构函数调用。为什么你会惊讶于析构函数被调用了两次? -
对不起,我应该删除复制构造函数和赋值运算符。虽然从某种意义上说我很高兴我没有这样做,因为那时你必须问这个:)
-
@LightnessRacesinOrbit 在熟练使用 Singleton 的写作和使用之后,他们可以继续 learning to avoid using them :)
标签: c++ design-patterns singleton destructor