简体   繁体   中英

why in singleton pattern , we do make copy constructor and assignment operator as private?

In a singleton pattern, typically we make the constructor/destructor private. That I understand because we don't want the user to create/delete the singleton object. There should be only way to get or create the instance. However, I don't understand why do we need to make the copy constructor and assignment operator as private. What is the advantage of making the copy constructor and assignment operator private in singleton.

Singleton obj1 = Singleton::CreateInstacnce();
    Singleton obj2 = obj1; // copy ctr gets called
    Singleton obj3;
    obj3 = obj1;  // assignment operator gets called

Therefore, if you don't make them private, multiple instance of Singleton class will be created

If you copy a singleton, you will have two objects of the same type. The purpose of singleton is to enforce only one instance. Copying would break that assumption.

In a singleton pattern, we just want to instantiate only one object. As you said, we we don't want the user to create/delete the singleton object, and we also don't want the user to copy the second object.

Singleton obj1 = Singleton::CreateInstacnce();
    Singleton obj2 = obj1; // copy ctr gets called
    Singleton obj3;
    obj3 = obj1;  // assignment operator gets called

Here as per my opinion I feel only copy ctr should be private along with constructor.

No need to make Assignment operator as private since Singleton obj3; will anyways give the error saying that Singleton () is private.

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