单例模式通过局部静态变量实现线程安全,C++11保证其初始化唯一性,推荐使用Meyers' Singleton方式,简洁且自动管理生命周期。

单例模式确保一个类只有一个实例,并提供全局访问点。在C++中实现线程安全的单例模式,推荐使用“局部静态变量 + 函数内定义”的方式,这是最简洁且线程安全的做法。
C++11 标准规定:函数内的局部静态变量初始化是线程安全的,多个线程同时调用该函数时,只会初始化一次。利用这一特性可以轻松写出线程安全的单例。
class Singleton { private: Singleton() = default; // 禁止外部构造 ~Singleton() = default; // 析构函数私有化 Singleton(const Singleton&) = delete; // 禁止拷贝 Singleton& operator=(const Singleton&) = delete; // 禁止赋值 public: static Singleton& getInstance() { static Singleton instance; // 局部静态变量,C++11 线程安全 return instance; } };使用方式:
Singleton& s1 = Singleton::getInstance(); Singleton& s2 = Singleton::getInstance(); // s1 和 s2 是同一个对象在C++11之前,常用双检锁(Double-Checked Locking)配合互斥锁实现线程安全。但现在已有更优解,仅作了解。
立即学习“C++免费学习笔记(深入)”;
#include <mutex> class Singleton { private: static std::unique_ptr<Singleton> instance; static std::mutex mtx; Singleton() = default; ~Singleton() = default; Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; public: static Singleton& getInstance() { if (instance == nullptr) { std::lock_guard<std::mutex> lock(mtx); if (instance == nullptr) { instance.reset(new Singleton); } } return *instance; } }; // 静态成员定义 std::unique_ptr<Singleton> Singleton::instance = nullptr; std::mutex Singleton::mtx;这种写法复杂且容易出错,比如内存重排序问题(需用内存屏障),不如局部静态变量简洁可靠。
以上就是c++++如何实现单例设计模式_c++线程安全的单例模式写法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号