考虑以下代码:
#include <iostream>
class Singleton
{
public:
// GetInstance returns an instance to an existing Singleton object
static Singleton& GetInstance()
{
static Singleton instance;
return instance;
}
// Destructor
~Singleton()
{
std::cout << "Singleton destructor" << std::endl;
}
private:
// Private constructor
Singleton()
{
std::cout << "Singleton constructor" << std::endl;
}
};
int main()
{
Singleton mySingleton = Singleton::GetInstance();
return 0;
}
这个的输出是:
Singleton constructor
Singleton destructor
Singleton destructor
似乎mySingleton
正在清理引用变量,因此调用了析构函数两次。有什么办法可以避免这种行为?