单例模式确保类唯一实例并提供全局访问点。C++中常见实现有:懒汉式加锁保证线程安全但性能较差;饿汉式程序启动即创建,线程安全但可能浪费资源;局部静态变量法利用C++11特性,延迟初始化且自动线程安全,推荐使用;带显式销毁的版本结合智能指针与锁,支持手动释放资源,适用于需精细控制生命周期的场景。选择方式应根据线程安全、性能和资源管理需求权衡。

单例模式是一种常用的设计模式,它确保一个类只有一个实例,并提供一个全局访问点。在C++中实现单例模式需要注意线程安全、构造顺序和资源释放等问题。下面介绍几种常见的C++单例模式实现方式。
懒汉式指的是在第一次使用时才创建实例。为了保证多线程环境下的安全,需要加锁控制。
示例代码:
#include <mutex>
<p>class Singleton {
private:
static std::unique_ptr<Singleton> instance;
static std::mutex mtx;</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 私有构造函数,防止外部实例化
Singleton() = default;public: // 删除拷贝构造和赋值操作 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete;
static Singleton* getInstance() {
std::lock_guard<std::mutex> lock(mtx);
if (!instance) {
instance.reset(new Singleton);
}
return instance.get();
}};
// 静态成员定义 std::unique_ptr<Singleton> Singleton::instance = nullptr; std::mutex Singleton::mtx;
这种方式保证了线程安全,但每次调用 getInstance 都会加锁,影响性能。
立即学习“C++免费学习笔记(深入)”;
饿汉式在程序启动时就创建实例,天然线程安全,适用于对象初始化开销不大且一定会使用的场景。
class Singleton {
private:
static Singleton instance;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">Singleton() = default;public: Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete;
static Singleton* getInstance() {
return &instance;
}};
// 全局初始化 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;
}};
这个方法既避免了手动加锁,又实现了延迟初始化,编译器会自动处理线程安全问题,是目前最推荐的方式。
有些场景下需要显式释放单例资源,比如日志系统或数据库连接池。可以结合智能指针和自定义删除器。
class Singleton {
private:
static std::shared_ptr<Singleton> instance;
static std::mutex mtx;
<pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">Singleton() = default;public: ~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static std::shared_ptr<Singleton> getInstance() {
std::lock_guard<std::mutex> lock(mtx);
if (!instance) {
instance = std::shared_ptr<Singleton>(new Singleton, [](Singleton* p) {
delete p;
});
}
return instance;
}
static void destroy() {
std::lock_guard<std::mutex> lock(mtx);
instance.reset();
}};
这种方式允许手动释放资源,适合生命周期管理要求严格的场景。
基本上就这些。选择哪种方式取决于具体需求:如果追求简洁高效,推荐局部静态变量法;若需控制销毁时机,可使用智能指针配合锁机制。单例模式虽简单,但在多线程和复杂系统中仍需谨慎使用,避免产生耦合和测试困难。
以上就是c++++怎么实现单例模式_C++设计模式之单例模式实现详解的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号