单例模式精写
懒汉模式
版本1:
class LazySingleton {
private:
static LazySingleton* instance;
static std::mutex mtx; // 用于线程安全
LazySingleton() = default;
~LazySingleton() = default;
LazySingleton(const LazySingleton&) = delete;
LazySingleton& operator=(const LazySingleton&) = delete;
public:
// 线程安全的懒汉模式 - 双重检查锁定
static LazySingleton* getInstance() {
if (instance == nullptr) { // 第一次检查,避免不必要的锁
std::lock_guard<std::mutex> lock(mtx);
if (instance == nullptr) { // 第二次检查,确保线程安全
instance = new LazySingleton();
}
}
return instance;
}
};
// 初始化静态成员
LazySingleton* LazySingleton::instance = nullptr;
std::mutex LazySingleton::mtx;
版本2:手动释放堆上内存
class LazySingleton {
private:
static LazySingleton* instance;
static std::mutex mtx;
