我正在用 C++ 实现 Singleton 类,我想知道是否有必要将复制构造函数和赋值运算符声明为私有(private),以防我有以下实现
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=
都是无用的。所以,我可以跳过将这些声明为私有(private)的,我错了吗?
最佳答案
没有什么可以阻止某人写作
Singleton hahaNotReallyASingleton = *Singleton::getInstance();
具体可以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
};
请注意,以这种方式使用 delete
是 C++11
及更高版本 - 如果您坚持使用较旧的代码库,则可以将函数设为 private
(只复制,当然不移动),或者继承自 boost:noncopyable
(感谢 badola)。
关于c++ - 禁止复制构造函数和赋值运算符单例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51375251/