单例模式确保类仅一个实例并提供全局访问,C++中推荐使用局部静态变量实现线程安全单例,因C++11保证其初始化线程安全、简洁高效;双重检查锁定模式虽性能优但易错,需原子操作与内存序控制,复杂不推荐。

单例模式确保一个类只有一个实例,并提供全局访问点。在C++中,实现线程安全的单例模式需要考虑多线程环境下的初始化竞争问题。最经典且高效的方式是使用“延迟初始化 + 局部静态变量”或“双重检查锁定模式(DCLP)”,但两者有重要区别。
代码示例:
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance; // 线程安全,C++11标准保证
return instance;
}
<pre class='brush:php;toolbar:false;'>Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;private: Singleton() = default; ~Singleton() = default; }; 优点:简洁、无需手动加锁、自动析构、线程安全。强烈推荐用于现代C++项目。
错误示例(非线程安全):
class SingletonBad {
static SingletonBad* instance;
static std::mutex mtx;
<p>public:
static SingletonBad* getInstance() {
if (instance == nullptr) { // 第一次检查
std::lock_guard<std::mutex> lock(mtx);
if (instance == nullptr) { // 第二次检查
instance = new SingletonBad;
}
}
return instance;
}
};
#include <atomic>
#include <mutex>
<p>class SingletonDCLP {
static std::atomic<SingletonDCLP*> instance;
static std::mutex mtx;</p><p>public:
static SingletonDCLP<em> getInstance() {
SingletonDCLP</em> tmp = instance.load(std::memory_order_relaxed);
if (tmp == nullptr) {
std::lock_guard<std::mutex> lock(mtx);
tmp = instance.load(std::memory_order_relaxed);
if (tmp == nullptr) {
tmp = new SingletonDCLP();
instance.store(tmp, std::memory_order_release);
}
}
return tmp;
}</p><pre class='brush:php;toolbar:false;'>SingletonDCLP(const SingletonDCLP&) = delete;
SingletonDCLP& operator=(const SingletonDCLP&) = delete;private: SingletonDCLP() = default; }; // 静态成员定义 std::atomic<SingletonDCLP*> SingletonDCLP::instance{nullptr}; 说明:使用原子指针配合互斥锁和内存序控制,可实现高性能线程安全DCLP。但复杂度高,易出错。
基本上就这些。
立即学习“C++免费学习笔记(深入)”;
以上就是C++单例模式实现方法_C++线程安全的单例模式写法与DCLP探讨的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号