4
votes

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?

2
Wrong question. Correct question is: why this darn and stupid Singleton exists in the first place?SergeyA
@SergeyA: Because it's in the GoF book :)Christian Hackl

2 Answers

8
votes

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.

-1
votes

A private destructor does nothing useful, here.

For the copy constructor and an assignment operator, you already answered your own question by diligently reproducing the comments next to them, in the shown code. Just read the comments. The only thing to add there, is that this code must precede C++11, because these days you'll just delete them.