需要对Singleton类中的赋值运算符进行私有化 [英] Need of privatizing assignment operator in a Singleton class
本文介绍了需要对Singleton类中的赋值运算符进行私有化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以证明在Singleton类实现中私有化赋值运算符的必要性吗?
Can someone justify the need of privatizing the assignment operator in a Singleton class implementation?
通过将Singleton& operator=(Singleton const&);
设为私有可以解决什么问题?
What problem does it solve by making Singleton& operator=(Singleton const&);
private?
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
};
推荐答案
对单身人士的分配只是一种无意义的操作,因为应该只存在一个对象.
Assignment on a singleton is simply a nonsense operation since only one object of it should ever exist.
将分配运算符设为私有可帮助诊断诸如以下内容的废话代码:
Making the assignment operator private helps diagnose nonsense code such as the following:
Singleton& a = Singleton::Instance();
Singleton& b = Singleton::Instance();
a = b; // Oops, accidental assignment.
这篇关于需要对Singleton类中的赋值运算符进行私有化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文