Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need of privatizing assignment operator in a Singleton class

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

What problem does it solve by making Singleton& operator=(Singleton const&); private?

class Singleton {
public:
  static Singleton& Instance() {
    static Singleton theSingleton;
    return theSingleton;
  }

private:
  Singleton(); // ctor hidden
  Singleton(Singleton const&); // copy ctor hidden
  Singleton& operator=(Singleton const&); // assign op. hidden
  ~Singleton(); // dtor hidden
};
like image 914
Prashanth G N Avatar asked Jul 12 '11 15:07

Prashanth G N


People also ask

Why do we need assignment operators?

Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value.

Why does Singleton pattern contain private constructors?

The private constructor in Java is used to create a singleton class. A singleton class is a class in Java that limits the number of objects of the declared class to one. A private constructor in Java ensures that only one object is created at a time.

Can we have singleton without private constructor?

A singleton cannot be made without a private constructor! If a class has a public constructor, then anybody can create an instance of it at any time, that would make it not a singleton. In order for it to be a singleton there can only be one instance.

What is the use of private constructor in singleton class C#?

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.


2 Answers

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.
like image 192
Konrad Rudolph Avatar answered Nov 10 '22 00:11

Konrad Rudolph


If you only want one instance, the copy constructor should be private. The assignment operator access specifier does not matter, because it will be impossible to use anyway.

like image 43
Alok Save Avatar answered Nov 10 '22 00:11

Alok Save