要防止C++单例类被拷贝,可以通过禁用拷贝构造函数和赋值操作符来实现。具体方法如下:
class Singleton {
private:
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
// 其他成员函数
void doSomething() {}
};
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
// 其他成员函数
void doSomething() {}
private:
Singleton() {}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
通过以上方法,可以有效地防止C++单例类被拷贝,确保只有一个实例存在并且可以通过getInstance()方法获取该实例。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:C++单例类会有哪些问题