1

I am implementing Singleton class in c++ and I am wondering if it is necessary to declare copy constructor and assignment operator as private, in case I have the following implementation

class Singleton{ static Singleton* instance; Singleton(){} public: static Singleton* getInstance(); }; Singleton* Singleton::instance = 0; Singleton* Singleton::getInstance(){ if(instance == 0){ instance = new Singleton(); } return instance; } 

It seems that I can have only pointer to Singleton and in that case copy constructor is useless, also operator= . So, I can skip declaring these as private, am I wrong ?

2
  • 1
    Possible duplicate of why explicitly delete the constructor? Commented Jul 17, 2018 at 7:12
  • 1
    If you don't want those operations or they are not valid/sane for the class, then you should =delete; the functions. Commented Jul 17, 2018 at 7:12

1 Answer 1

3

There's nothing to stop someone writing

Singleton hahaNotReallyASingleton = *Singleton::getInstance(); 

You can specifically mark these functions as deleted:

class Singleton { // ... other bits ... Singleton(Singleton const&) = delete; // copy ctor Singleton(Singleton &&) = delete; // move ctor Singleton& operator=(Singleton const&) = delete; // copy assignment Singleton& operator=(Singleton &&) = delete; // move assignment }; 

Note that using delete in this way is C++11 and onwards - if you are stuck with an older codebase, you could make the functions private (copy only, not move of course), or inherit from boost:noncopyable (thanks badola).

Sign up to request clarification or add additional context in comments.

2 Comments

thank you, I haven't considered that case, I thought I cannot have object of that class
Kindly note that deleted functions are only allowed C++11 and above. For pre-C++11, a construct similar to boost::noncopyable would be required.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.