单例模式确保类唯一实例并提供全局访问点,C++中常用局部静态变量实现(C++11起线程安全),推荐该方式因其简洁且自动管理生命周期,避免手动释放与多线程问题。

单例模式是一种常用的创建型设计模式,确保一个类只有一个实例,并提供一个全局访问点。在C++中实现单例模式需要注意线程安全、构造顺序和资源释放等问题。下面介绍几种常见的实现方式。
懒汉模式(基础版)
懒汉模式在第一次使用时才创建实例。
class Singleton {private:
static Singleton* instance;
Singleton() {} // 私有构造函数
public:
static Singleton* getInstance() {
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
这种方式在多线程环境下不安全,可能多个线程同时进入判断并创建多个实例。
线程安全的懒汉模式(加锁)
使用互斥锁保证多线程下只创建一次。
立即学习“C++免费学习笔记(深入)”;
#includeclass Singleton {
private:
static Singleton* instance;
static std::mutex mtx;
Singleton() {}
public:
static Singleton* getInstance() {
std::lock_guard<:mutex> lock(mtx);
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;
虽然线程安全,但每次调用都加锁影响性能。可以结合双重检查锁定优化。
双重检查锁定(Double-Checked Locking)
减少锁的开销,仅在初始化时加锁。
static Singleton* getInstance() {if (instance == nullptr) {
std::lock_guard<:mutex> lock(mtx);
if (instance == nullptr) {
instance = new Singleton();
}
}
return instance;
}
注意:需要确保指针赋值是原子操作,C++11之后支持原子指针可进一步增强安全性。
饿汉模式(推荐简单场景)
在程序启动时就创建实例,天然线程安全。
class Singleton {private:
static Singleton instance;
Singleton() {}
public:
static Singleton& getInstance() {
return instance;
}
};
Singleton Singleton::instance;
优点是简单且线程安全,缺点是无法延迟加载,可能浪费资源。
局部静态变量(C++11 起推荐)
利用函数内静态变量的特性,最简洁且线程安全。
static Singleton& getInstance() {static Singleton instance;
return instance;
}
C++11标准规定局部静态变量的初始化是线程安全的。这种方式自动管理生命周期,无需手动释放,代码简洁可靠。
注意事项与建议
- 避免在构造函数中抛出异常,可能导致未定义行为
- 考虑是否需要支持继承,一般单例不应被继承
- 如果使用指针形式,需手动管理内存或使用智能指针
- 频繁调用的单例建议使用饿汉或局部静态变量方式
- 避免在多线程环境中销毁单例,除非明确控制生命周期
基本上就这些。对于大多数现代C++项目,推荐使用局部静态变量实现单例,既简洁又安全。











