C++ 超出返回引用的单例生存期
我和一位同事讨论了如何打造单身汉,结果发现我们的做法有所不同 我的单身汉:C++ 超出返回引用的单例生存期,c++,singleton,C++,Singleton,我和一位同事讨论了如何打造单身汉,结果发现我们的做法有所不同 我的单身汉: class Singleton { public: static Singleton* getInstance() { if(!instance) instance = new Singleton(); return instance; } ~Singleton() { if(instance) delete instance;
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() {}
};
他的独生子女:
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()
方法返回实例时,我们不是要离开声明它的范围并取消它的存储吗?你如何解释它的生命超出了代码>返回< /C> >?/P> < p>你需要检查C++中的存储类。
任何声明为static(或extern)的对象都有静态存储,并在程序结束时以与构造相反的顺序被销毁。
裸体静态对象的构造顺序是不确定的,并且很麻烦,特别是在多线程中。
函数局部静态对象(又名Scott Meyer的单例对象)是在第一次调用所属函数时构造的ALAP,并且由于C++11是在一个神奇的线程安全域中(即,没有双重构造)。
我会将以下声明添加到您朋友的类中,以使singleton真正单身:
class Singleton{
//...
Singleton(Singleton const&)=delete;
Singleton(Singleton&&)=delete;
auto& operator=(Singleton const&)=delete;
auto& operator=(Singleton &&)=delete;
};
你的C++书籍应该有完整的解释:<代码>静态< /COD>范围。(提示:不会)@UKMonkey-ooohoh。。。