I have seen that constructors, copy constructor, destructor and assignment operator is kept in private scope in a typical singletone class. e.g.
class CMySingleton
{
public:
static CMySingleton& Instance()
{
static CMySingleton singleton;
return singleton;
}
private:
CMySingleton() {} // Private constructor
~CMySingleton() {}
CMySingleton(const CMySingleton&); // Prevent copy-construction
CMySingleton& operator=(const CMySingleton&); // Prevent assignment
};
Now, my question is
why shoule we keep destructor and assignment operator in private scope? Is it mandatory?
Does a public destructor break any property of a singleton class? Because since our object construction is restricted so there is no chance of a unwanted destruction.
I can understand that private assignment operator can prevent a self assignment, but does a public assignment operator harm anyway other than extra run-time?
Similarly, you should assure the lifetime longevity of the Singleton instance by encapsulating its destructor in a private context.
What is the use of private destructor? Whenever we want to control the destruction of objects of a class, we make the destructor private. For dynamically created objects, it may happen that you pass a pointer to the object to a function and the function deletes the object.
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. It restricts the class instances within the declared class so that no class instance can be created outside the declared class.
When a class contains dynamic object then it is mandatory to write a destructor function to release memory before the class instance is destroyed this must be done to avoid memory leak.
Making the destructor private potentially prevents someone from trying to call delete
on a pointer to the singleton.
auto& singleton = CMySingleton::Instance();
auto pointer_to_singleton = &singleton;
delete pointer_to_singleton; // Bad!
Disabling the assignment operator prevents harmless but nonsensical self-assignment. See this answer. If someone is doing this, chances are, it was a mistake so you might as well prevent it.
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