C ++ singleton - 什么时候被析构函数调用?

时间:2017-04-27 15:40:28

标签: c++ singleton

以下似乎是在C ++中定义单例的推荐方法:

class Singleton {
private:

    Singleton();

public:
    static Singleton & get_instance() {
        static Singleton instance;
        return instance;
    }

     ~Singleton() {
        // destructor
     }

    Singleton(Singleton const&) = delete;
    void operator=(Singleton const&) = delete;
}

现在,请使用此功能:

void foo() {
   Singleton & s = Singleton::get_instance();
}

我期望在单例实例超出该函数范围时调用析构函数,但事实并非如此。析构函数什么时候被调用?

1 个答案:

答案 0 :(得分:1)

不,因为get_instance()返回Singleton对象的引用,所以不会调用析构函数,该引用会保存到另一个引用s中。这两个引用都指向静态Singleton对象,即:

static Singleton instance;

所以,这里只有一个对象,instance。传递引用不会创建新对象,因此不会调用析构函数。

对象instance将被销毁,因此,它的析构函数将在程序终止时被调用(因为它是static)。