单身寿命超出返回参考

时间:2018-04-16 12:17:35

标签: c++ singleton

一位同事和我正在讨论如何制作一个单身人士,事实证明我们的做法不同。

我的单身人士:

class Singleton
{
public:
    static Singleton* getInstance() 
    {
        if(!instance) instance = new Singleton();
        return instance;
    }
    ~Singleton()
    {
        if(instance) delete instance;
    }

private:
    Singleton() {}
    static Singleton* instance;
};

他的单身人士:

class Singleton
{
public:
    static Singleton& getInstance() 
    {
        static Singleton instance;
        return instance;
    }
private:
    Singleton() {}
};

这些示例当然是为了阅读目的而简化的。我喜欢他的解决方案,因为它更短,而且更优雅,但有些东西让我烦恼......

当他的getInstance()方法返回实例时,我们不是要离开声明它的范围并将其去除吗?你怎么解释它的寿命超过return

1 个答案:

答案 0 :(得分:2)

您需要在C ++中查看存储类。 声明为static(或extern)的任何对象都具有静态存储,并在程序结束时以相反的构造顺序被破坏。 裸露静物的构造顺序不确定且麻烦,特别是在多线程中。 函数本地静态对象(AKA Scott Meyer的单例)OTH是在第一次调用拥有函数时构造的ALAP,并且因为C ++ 11是一个神奇的线程安全庄园(即没有双重构造)。 我会将以下声明添加到您朋友的课程中,以使单身实际单身:

class Singleton{
    //...
    Singleton(Singleton const&)=delete;
    Singleton(Singleton&&)=delete;
    auto& operator=(Singleton const&)=delete;
    auto& operator=(Singleton &&)=delete;
};