单例模式通过私有构造函数、删除拷贝操作和静态成员实现全局唯一实例。C++11推荐使用局部静态变量实现线程安全的懒汉模式,代码简洁且自动管理生命周期;饿汉模式在程序启动时创建实例,适用于初始化简单且必用场景;旧版本C++可采用互斥锁加双重检查锁定实现线程安全的懒加载,但需手动管理内存,易出错。建议优先使用C++11局部静态方式,避免动态内存分配,确保安全高效。

在C++中实现单例模式的关键是确保一个类只有一个实例,并提供一个全局访问点。同时要处理好线程安全、构造顺序和资源释放等问题。以下是几种常见且正确的实现方式。
说明: C++11标准规定局部静态变量的初始化是线程安全的,多个线程同时调用该函数时,只会初始化一次。
代码示例:
class Singleton { public: static Singleton& getInstance() { static Singleton instance; // 局部静态变量,自动管理生命周期 return instance; }Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete;
private:
Singleton() = default; // 私有构造函数
~Singleton() = default;
};
说明: 实例在main函数运行前完成构造,不存在多线程竞争问题,但可能造成资源浪费。
立即学习“C++免费学习笔记(深入)”;
实现方法:
class Singleton { public: static Singleton& getInstance() { return instance; }Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete;
private:
Singleton() = default;
~Singleton() = default;
static Singleton instance; // 静态成员,在程序启动时构造
};
// 定义静态成员
Singleton Singleton::instance;
注意: 虽然能工作,但不如C++11的局部静态简洁高效,容易出错。
示例代码:
#include <mutex>class Singleton {
public:
static Singleton* getInstance() {
if (instance == nullptr) {
std::lockguard<std::mutex> lock(mutex);
if (instance == nullptr) {
instance = new Singleton();
}
}
return instance;
}
Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete;
private:
Singleton() = default;
~Singleton() = default;
static Singleton* instance; static std::mutex mutex_;
};
// 静态成员定义
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mutex_;
这种写法需要手动管理内存,建议配合智能指针或添加释放接口。
基本上就这些。正确实现单例不复杂,关键是选对方法,兼顾安全与简洁。
以上就是c++++中如何正确地实现一个单例模式_c++单例设计模式实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号