[英]prohibit copy constructor and assignment operator singleton class
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 我正在用C ++实现Singleton类,我想知道是否有必要将复制构造函数和赋值运算符声明为私有,以防万一我具有以下实现
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=
. 看来我只能有一个指向Singleton的指针,在这种情况下,复制构造函数是无用的,也是
operator=
。 So, I can skip declaring these as private, am I wrong ? 因此,我可以跳过将它们声明为私有的操作,我错了吗?
There's nothing to stop someone writing 没有什么可以阻止某人写作
Singleton hahaNotReallyASingleton = *Singleton::getInstance();
You can specifically mark these functions as delete
d : 您可以将这些功能专门标记为
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 ). 请注意,以这种方式使用
delete
是C++11
及更高版本-如果您使用的是较旧的代码库,则可以将函数设为 private
(仅复制,当然不移动),或从boost:noncopyable
继承(感谢badola ) 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.