Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why private destructor in a Singleton class?

Tags:

c++

singleton

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?

like image 561
paper.plane Avatar asked Jun 05 '16 13:06

paper.plane


People also ask

Should destructor be private in Singleton?

Similarly, you should assure the lifetime longevity of the Singleton instance by encapsulating its destructor in a private context.

Why do we need private destructor?

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.

Why do we make constructor private in 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. It restricts the class instances within the declared class so that no class instance can be created outside the declared class.

In which case is it mandatory to private a destructor in a 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.


1 Answers

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.

like image 145
Chris Drew Avatar answered Oct 04 '22 00:10

Chris Drew