C++单例实现

本文介绍了C++中单例模式的两种实现方法,包括使用`static`保证实例唯一和利用`std::call_once`确保初始化仅执行一次。
摘要由CSDN通过智能技术生成

单例模式确保一个类的实例话只能有一个对象,单例模式在日志系统,数据库操作中比较常见。常见的饿汉模式和懒汉模式不在过多介绍,以下是C++11实现单例的方式,一种是使用static确保只有一个实例,一种是利用call_once确保只执行一次初始化。

#include <iostream>
#include <mutex>
class Singleton
{
public:
	static Singleton& GetInstance()
	{
		static Singleton instance;
		return instance;
	}
	Singleton(const Singleton&) = delete;
	Singleton& operator=(const Singleton&) = delete;
private:
	Singleton() = default;
};
class Singleton
{
public:
	Singleton(const Singleton&) = delete;
	Singleton& operator=(const Singleton&) = delete;
	static Singleton* GetInstance()
	{
		std::call_once(m_flg, [&]() 
			{
				m_instance = new Singleton;
			});
		return m_instance;
	}//使用call_once确保只会执行一次,也就是只会执行一次m_instance = new Singleton;
private:
	Singleton() = default;
	static std::once_flag m_flg;
	static Singleton* m_instance ;
};
std::once_flag Singleton::m_flg;
Singleton* Singleton::m_instance = nullptr; //类中定义的static需要在类外初始化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值