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

本文详细介绍了如何在C++中实现一个线程安全的单例模式,确保在多线程环境下正确且唯一地创建实例。同时,探讨了单例模式在资源管理上的应用,包括如何在程序退出时优雅地释放资源,以避免内存泄漏问题。通过实例代码和分析,读者将深入理解C++单例模式的设计和实现技巧。
摘要由CSDN通过智能技术生成
//非线程安全;
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 SingletonLaz
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值