c++中单例实现
单例(Singleton)是一种常见的设计模式,它保证一个类只有一个实例,并提供一个全局访问点。
C++中单例的实现有多种方式,以下是其中两种常见的实现方式:
- 饿汉式单例
饿汉式单例是在程序启动时就创建对象实例,以保证在任何时候都只有一个对象实例。这种方式的缺点是可能造成资源浪费,因为对象实例在程序启动时就被创建出来了,即使后续程序并不需要使用该对象实例。
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
// 禁止拷贝和赋值操作
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() {} // 私有构造函数
};
- 懒汉式单例
懒汉式单例则是在需要使用对象实例时才去创建对象实例,以避免不必要的资源浪费。但是这种方式需要考虑线程安全问题,否则可能会出现多个线程同时创建对象实例的情况,从而破坏单例实例的唯一性。
class Singleton {
public:
static Singleton& getInstance() {
static Singleton* instance = nullptr;
if (instance == nullptr) {
std::lock_guard<std::mutex> lock(mutex_);
if (instance == nullptr) {
instance = new Singleton();
}
}
return *instance;
}
// 禁止拷贝和赋值操作
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() {} // 私有构造函数
static std::mutex mutex_;
};
std::mutex Singleton::mutex_;
以上两种实现方式都将构造函数设置为私有,以避免外部直接创建对象实例。同时,为了防止拷贝和赋值操作,还需要将拷贝构造函数和赋值运算符设置为delete。在多线程环境下,懒汉式单例需要使用锁来保证线程安全
原文地址: http://www.cveoy.top/t/topic/hlK3 著作权归作者所有。请勿转载和采集!