需要在Singleton类中私有化赋值运算符

Pra*_*G N 7 c++ singleton assignment-operator

有人可以证明在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
};
Run Code Online (Sandbox Code Playgroud)

Kon*_*lph 11

单身人士的分配只是一个无意义的操作,因为它只应该存在一个对象.

将赋值运算符设置为私有有助于诊断无意义的代码,例如:

Singleton& a = Singleton::Instance();
Singleton& b = Singleton::Instance();
a = b; // Oops, accidental assignment.
Run Code Online (Sandbox Code Playgroud)

  • 即使开发人员做a = b,我也明白 没有任何伤害,因为两个对象都指向Singleton的相同静态实例.因此,私有化或赋值运算符不是单身人员按预期行事的必要条件. (3认同)