需要私有化单例类中的赋值运算符 [英] Need of privatizing assignment operator in a Singleton class
本文介绍了需要私有化单例类中的赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以证明在单例类实现中私有化赋值运算符的必要性吗?
Can someone justify the need of privatizing the assignment operator in a Singleton class implementation?
制作Singleton&它解决了什么问题operator=(Singleton const&);
private?
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.
这篇关于需要私有化单例类中的赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文