-1

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.

user3629119
  • 151
  • 1
  • 9
  • Consider what the default access is of both the copy-ctor and the assignment-operator is if *not* declared *at all*. – WhozCraig Nov 20 '14 at 06:49
  • Check here http://stackoverflow.com/questions/6666413/need-of-privatizing-assignment-operator-in-a-singleton-class – Ramesh Chander Nov 20 '14 at 06:52

4 Answers4

2
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

user966379
  • 2,823
  • 3
  • 24
  • 30
  • Singleton obj3; we can't do this as it implicates that we are creating an object of class that will be not permitted as constructor is private. – Ankit Feb 11 '16 at 09:00
1

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.

Germán Diago
  • 7,473
  • 1
  • 36
  • 59
0

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.

Kill Console
  • 1,933
  • 18
  • 15
0
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.

Mohit Tak
  • 1
  • 2