简体   繁体   中英

Use of copy constructor and assignment operator in singleton design pattern

My doubt in Singleton design pattern is if it's enough to just make the constructor private. I think there is no need to make the copy constructor and assignment operator private.

Since we can not create the object, (object will be created by a static function and will be allocated in static pointer) then the copy constructor or assignment operator will not be invoked. Is this right?

That's wrong. If you receive a pointer to an internally allocated instance, you could still make a copy of it if the copy constructor is public. For example:

Singleton * s = Singleton::getInstance();

Singleton copy = *s;   // <-- invokes copy constructor

Similar problem with the assignment operator:

Singleton * s1 = Singleton::getInstance();
Singleton * s2 = Singleton::getInstance();

*s1 = *s2;    // <-- invokes assignment operator (although self-assignment...)

Both of these won't do much harm, but they're violating the intent of the Singleton pattern.

By making both copy constructor and assignment operator private, you solve the problem. Since C++11, you can also "delete" them, by writing

Singleton(const Singleton&) = delete;               // copy constructor
Singleton & operator=(const Singleton&) = delete;   // assignment operator

No need to make the copy constructor (and assignment operator) private, as by default they would use shallow copy. However, why would you want to implement a copy constructor in a Singleton class? If you implement a copy constructor, and implement deep copying in it, and keep it public, well, then multiple objects of the class can be created.

If you are using C++11, best would be to delete them:

MyClass (MyClass const &) = delete;
MyClass & operator = (MyClass const &) = delete;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM