有人可以证明在 Singleton 类实现中私有化赋值运算符的必要性吗?
它解决了什么问题Singleton& operator=(Singleton const&);
私人的?
class Singleton {
public:
static Singleton& Instance() {
static Singleton theSingleton;
return theSingleton;
}
private:
Singleton(); // ctor hidden
Singleton(Singleton const&); // copy ctor hidden
Singleton& operator=(Singleton const&); // assign op. hidden
~Singleton(); // dtor hidden
};
对单例进行赋值只是一种无意义的操作,因为它只应该存在一个对象。
将赋值运算符设置为私有有助于诊断如下无意义代码:
Singleton& a = Singleton::Instance();
Singleton& b = Singleton::Instance();
a = b; // Oops, accidental assignment.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)