禁止复制构造函数和赋值运算符singleton类



我正在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;
} 

似乎我只能有一个指向Singleton的指针,在这种情况下,复制构造函数是无用的,也是operator=。所以,我可以跳过将这些声明为私有的,我错了吗?

没有什么可以阻止某人编写

Singleton hahaNotReallyASingleton = *Singleton::getInstance();

您可以将这些函数具体标记为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
};

请注意,以这种方式使用deleteC++11及以后的函数-如果您使用旧的代码库,您可以使函数private(仅复制,当然不能移动(,或从boost:noncopyable继承(感谢badola(。

最新更新