单例模式-简单线程安全的实现方式

/***
 * 为什么说 饿汉式是线程安全的
 * 因为在线程访问之前,单例类就已经创建好自己的实例的引用了 ,并且再一个生命周期中一个类只会被加载化一次
使用场景:
有状态的工具类对象
频繁访问文件或者数据库的类对象
 ****/
#include <iostream>
using namespace std;

class Single
{
	public:
		static Single *Getinstance(void); 
		void sngt_tst(void);

	private:
		static Single m_singt;
		
		//operator = 是为了 防止产生拷贝构造函数
		// 如果直接 用Single:: Getinstance() 就可以省掉下面两句了
		Single(const Single &);
		Single& operator = (const Single &);
		Single(){
			cout<< "creat Single" <<endl;
		}
		~Single(){
			cout << "destroy Single" <<endl;
		}
};
// 使用饿汉式 先创建再使用 空间换时间
Single Single::m_singt;
// 用这个指针类型的防止内存泄漏
Single *Single:: Getinstance()
{
	return &m_singt;
}

void Single :: sngt_tst()
{
	cout<< "single fuctoin call" <<endl;

}

int main()
{
	Single *singt1 = Single :: Getinstance();
	Single *singt2 = Single :: Getinstance();
	singt2->sngt_tst();
	Single:: Getinstance()->sngt_tst();//用这个 可以不用 重载 = 了
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值