懒汉式推荐使用局部静态变量,线程安全且延迟初始化;2. 饿汉式在程序启动时创建实例,天然线程安全但可能浪费资源;3. 带智能指针和互斥锁的懒加载适用于需手动管理生命周期的复杂场景;4. 现代C++首选局部静态变量实现,简洁高效,避免滥用单例降低耦合。

在C++中实现单例模式的关键是确保一个类只有一个实例,并提供一个全局访问点。常见的做法包括私有化构造函数、删除拷贝控制成员,以及提供静态方法获取唯一实例。以下是几种常用且有效的实现方式。
懒汉式在第一次调用时才创建实例,适合不频繁使用的场景。使用局部静态变量可保证线程安全(C++11起)。
<pre class="brush:php;toolbar:false;">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; // 可选析构
};
这种方式简洁、高效,推荐在现代C++中使用。局部静态变量的初始化由编译器保证线程安全,无需手动加锁。
饿汉式在程序启动时就创建实例,适用于确定会使用的全局对象。
立即学习“C++免费学习笔记(深入)”;
<pre class="brush:php;toolbar:false;">class Singleton {
public:
static Singleton& getInstance() {
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() = default;
static Singleton instance; // 程序启动时构造
};
// 定义静态成员
Singleton Singleton::instance;
由于实例在main函数前构造,不存在多线程竞争问题,天然线程安全,但可能造成资源浪费。
如果需要更灵活的控制,可以结合std::unique_ptr和互斥锁实现延迟加载。
<pre class="brush:php;toolbar:false;">#include <memory>
#include <mutex>
class Singleton {
public:
static std::shared_ptr<Singleton> getInstance() {
if (!instance) {
std::lock_guard<std::mutex> lock(mutex_);
if (!instance) {
instance = std::make_shared<Singleton>();
}
}
return instance;
}
private:
Singleton() = default;
static std::shared_ptr<Singleton> instance;
static std::mutex mutex_;
};
// 静态成员定义
std::shared_ptr<Singleton> Singleton::instance = nullptr;
std::mutex Singleton::mutex_;
这种方式支持延迟初始化,同时通过锁保证多线程安全,适用于复杂场景,但代码稍显繁琐。
现代C++推荐使用局部静态变量的懒汉式,写法简单,线程安全,延迟加载,性能好。除非有特殊需求,如需要动态释放资源或跨平台兼容旧标准,否则不必使用复杂方案。单例模式虽方便,但应谨慎使用,避免滥用导致耦合度升高。
基本上就这些,掌握一种可靠写法即可应对大多数情况。
以上就是c++++怎么实现一个单例模式_c++设计模式中的全局唯一实例实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号