Need of privatizing assignment operator in a Singleton class

前端 未结 7 1057
一生所求
一生所求 2021-01-18 04:01

Can someone justify the need of privatizing the assignment operator in a Singleton class implementation?

What problem does it solve by making Singleton& o

7条回答
  •  一个人的身影
    2021-01-18 04:48

    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.
    

提交回复
热议问题