5

I have a project in C++ and learning design pattern along the way (I'm very new to C++). I had a situation where I thought that a singleton would be a solution. (Now wait wait wait before you all go: singletons are baaaaaad. Let's all down vote and burn that heretic user!!!!)

I ran the example found here: https://stackoverflow.com/a/1008289/2336887

...but am getting an error when using the C++ 11 version.

My question is not whether Singleton should or not be used. It has been covered more than enough.

My question is: Why delete the public constructor and not simply the keep the private one? If it stays there, the error call to deleted constructor occurs. I don't understand and it frustrates me not to. Could somebody shed some light on a C++ newbie?

Here is the code to avoid going to the other post:

 class S {
 public:
     static S& getInstance(){
         static S    instance; 
         return instance;
     }
 private:
     S() {}

 public:
     S(S const&)               = delete;
     void operator=(S const&)  = delete;
 };



 int main() {
     S bus =  S::getInstance();
     return 0;
 }

Thanks for your help... and patience.

p.s.: I could have added the question to the original post, but at this point I think it would have brought more noise than anything.

BaldDude
  • 1,025
  • 1
  • 19
  • 33

2 Answers2

8

Why delete the public constructor and not simply the keep the private one?

The core idea of singleton is that there is only ever one instance. If copying of the object were allowed, then there could be more than one instance. That is why the copy constructor of a singleton is deleted: To make the singleton non-copyable.

If it stays there, the error call to deleted constructor occurs. I don't understand and it frustrates me not to.

There is an error because you try to copy a non-copyable object. Don't try to copy singletons. I suspect that you were suppsed to have a reference to the singleton instead:

S& bus = S::getInstance();
eerorika
  • 232,697
  • 12
  • 197
  • 326
5

Why delete the public constructor and not simply the keep the private one?

Because the public constructor is a copy constructor. That's being deleted because it isn't needed and should not be used. The private constructor is a default constructor, which is needed for internal use (at some point, a singleton must be constructed!)

Tim Randall
  • 4,040
  • 1
  • 17
  • 39