Need of privatizing assignment operator in a Singleton class

前端 未结 7 955
一生所求
一生所求 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:42

    There's only one singleton. It makes no sense to copy it. You need two things for a copy to be sane and most copy operators need to check for self==&other in order to be safe.

    This private trick is a hack. C++0x does it better.

    Begin rant...

    IMHO a Singleton is a contradiction in terms. It's a product of the silly idea that everything must be an object in order to be encapsulated. It's the same brainache that bore Java's Math.sin(x) et al.

    Your life will be simpler if the "singleton" is simply a set of free functions in a namespace. Any private "members" of the singleton can be hidden in an anonymous namespace in the .cpp. Encapsulation achieved, and you don't have that cumbersome extra syntax.

    MyNamespace :: foo ();
    

    instead of

    MyClass :: instance () .foo ();
    

提交回复
热议问题