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
};
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With