引用变量调用析构函数

时间:2013-02-21 21:43:00

标签: c++ variables reference singleton destructor

请考虑以下代码:

#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,从而调用析构函数两次。 有没有办法避免这种行为?

1 个答案:

答案 0 :(得分:3)

您正在此处制作实例的副本:

Singleton mySingleton = Singleton::GetInstance();

您也希望将复制构造函数和赋值运算符设为私有,这会强制您获取引用:

Singleton& mySingleton = Singleton::GetInstance();