单例模式确保类唯一实例并提供全局访问点。通过私有构造函数、删除拷贝操作,静态方法获取实例。饿汉式在程序启动时创建实例,线程安全,适合确定使用场景;示例中静态成员变量直接初始化。懒汉式延迟初始化,C++11起局部静态变量实现线程安全,推荐现代C++使用;代码简洁且无需手动管理锁。手动加锁版本需用互斥量保护动态创建过程,适用于旧编译器或复杂初始化,但易出错不推荐新手。总结:优先选用局部静态变量的懒汉式,其次饿汉式,避免手动加锁。

单例模式确保一个类只有一个实例,并提供一个全局访问点。在C++中实现单例模式,关键在于控制构造函数的访问权限、禁止拷贝,并通过静态方法返回唯一实例。
在程序启动时就创建实例,线程安全且实现简单。
特点: 实例在类加载时创建,不存在多线程竞争问题。示例代码:
class Singleton {
private:
static Singleton instance; // 唯一实例
Singleton() = default; // 私有构造函数
<p>public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">static Singleton& getInstance() {
return instance;
}
void doSomething() {
// 示例方法
}};
立即学习“C++免费学习笔记(深入)”;
// 静态成员定义 Singleton Singleton::instance;
延迟到第一次使用时才创建实例,适合资源敏感场景。需注意多线程环境下的安全性。
推荐方式: 利用局部静态变量的特性(C++11起保证线程安全)。示例代码:
class Singleton {
private:
Singleton() = default;
<p>public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">static Singleton& getInstance() {
static Singleton instance; // 局部静态变量,自动线程安全
return instance;
}
void doSomething() {
// 示例方法
}};
立即学习“C++免费学习笔记(深入)”;
适用于较老的编译器或需要更复杂初始化逻辑的情况。
需要引入互斥量来保证线程安全。
#include <mutex>
<p>class Singleton {
private:
static Singleton* instance;
static std::mutex mtx;
Singleton() = default;</p><p>public:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">static Singleton* getInstance() {
std::lock_guard<std::mutex> lock(mtx);
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}};
立即学习“C++免费学习笔记(深入)”;
// 静态成员定义 Singleton* Singleton::instance = nullptr; std::mutex Singleton::mtx;
基本上就这些。现代C++推荐使用局部静态变量的懒汉式写法,简洁又安全。饿汉式适合确定必须使用的场景,而手动加锁的方式虽然灵活但容易出错,不建议新手使用。
以上就是c++++中如何实现单例模式_设计模式之单例模式C++实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号