C++单例,线程安全,资源释放

本文详细介绍了如何在C++中实现一个线程安全的单例模式,确保在多线程环境下正确且唯一地创建实例。同时,探讨了单例模式在资源管理上的应用,包括如何在程序退出时优雅地释放资源,以避免内存泄漏问题。通过实例代码和分析,读者将深入理解C++单例模式的设计和实现技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//非线程安全;
class Singleton {
public:
	static Singleton& GetInstance() {
		static Singleton instance;//对象构造过程中可能线程切换到另一个线程;
		return instance;
	}
	void test() { cout << "test!!!" << endl; }
private:
	Singleton() {}
	Singleton(const Singleton& );
	Singleton& operator=(const Singleton& );
};

//懒汉模式:非线程安全,第一次调用才进行初始化;
class SingletonLazy {
public:
	static SingletonLazy* GetInstance() {
		if (spts == nullptr)
			// 有可能在此时出现线程切换,而此时spts为空;
			spts = new SingletonLazy();
		return spts;
	}
	void test() { cout << "class lazy!!!" << endl; }
private:
	static SingletonLazy* spts;
	SingletonLazy(){}
	SingletonLazy(const SingletonLazy&);
	SingletonLazy& operator=(const SingletonLazy&);
};

SingletonLazy* SingletonLazy::spts = nullptr;

//线程安全的懒汉模式:使用双检锁DCL机制
class SingletonLazySafe {
public:
	static SingletonLazySafe* GetInstance() {
		if (spts == nullptr) {
//因为spts = new SingletonLazySafe()这句指令的reorder导致
C++模式是一种常用的软件设计模式,它保证一个类只有一个实,并提供全局访问点。在创建和管理的过程中,确保线程安全和正确的生命周期至关重要,特别是涉及到资源的初始化、清理和销毁时。 一种常见的实现方法是“懒汉式”加载和“双重检查锁定”策略: 1. **懒汉式** (Lazy Initialization): ```cpp class Singleton { private: static Singleton* instance; public: // 防止多次构造 Singleton() = delete; Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static Singleton* getInstance() { if (!instance) { std::lock_guard<std::mutex> lock(singletonMutex); if (!instance) { instance = new Singleton(); } } return instance; } ~Singleton() { delete this; // 模式下,应该将析构函数内移,由外部手动删除 } }; ``` 这里用到了互斥锁(`std::mutex`),在第一次获取实时才初始化,避免了多线程同时创建多个实的问题。 2. **双重检查锁定** (Double-Check Locking): 这是一种改进版本,只有在确定没有其他线程尝试初始化的情况下才会加锁,进一步提高效率: ```cpp class Singleton { private: static Singleton* instance; static std::once_flag flag; Singleton() {} public: static Singleton* getInstance() { std::call_once(flag, []() { instance = new Singleton(); }); return instance; } }; ``` 通过`std::call_once`保证一次初始化,无需额外锁保护。 为了在程序结束时安全地释放,通常不需要手动删除,因为通常负责一些持久化的资源。但如果你在Singleton里持有一些需要手动释放的对象(如文件句柄、数据库连接等),应在`~Singleton()`中处理它们的清理工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值