Reputation: 131
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 ?
Upvotes: 1
Views: 1480
Reputation: 19767
There's nothing to stop someone writing
Singleton hahaNotReallyASingleton = *Singleton::getInstance();
You can specifically mark these functions as delete
d:
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).
Upvotes: 3