5

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?

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
paper.plane
  • 1,201
  • 10
  • 17

2 Answers2

9

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.

Community
  • 1
  • 1
Chris Drew
  • 14,926
  • 3
  • 34
  • 54
  • 1
    I have no doubt about the private ctor and copy-ctor. No new object can be created with a assignment operator. Does the public scope defeat the point apart from restricting a self assignment during compilation? – paper.plane Jun 05 '16 at 14:11
  • @paper.plane You are right. I've modified the answer to just consider assignment and destructor. – Chris Drew Jun 05 '16 at 14:23
-2

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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • 1
    I have no doubt about the private ctor and copy-ctor. No new object can be created with a public assignment operator. Does it break the singleton concept in anyway apart from restricting a self assignment during compilation? – paper.plane Jun 05 '16 at 14:13