基于c++新标准线程安全的单例模板实现

单例——在应用程序中某个类的实例只有一个,以便做全局访问点,这样可以协调系统的整体行为。也就是说提供访问某一资源(硬件设备、ini文件……)的统一接口。

在此只讨论基于c++新标准的一个线程安全实现。涉及到CRTP(Curiously Recurring Template Prattern)的使用。先看以下知识点:

1. c++新标准中指出:局部static变量的初始化是线程安全的。

2. CRTP 可以使类具备某些特性,这里利用此特性,使我们的类可以成为一个单例。(受std::enable_shared_from_this<T>启发)。

一、基类的定义

#ifndef SINGLETON_BASE_CPP_11_H
#define SINGLETON_BASE_CPP_11_H

#include <QDebug>

template<typename T>
class singleton {
public:
	static T *getInstance();
    virtual ~singleton(){};

protected:
	singleton(){};

	singleton(const singleton<T> &ref) = delete;
	singleton<T> &operator=(const singleton<T> &ref) = delete;
};

template<typename T>
T *singleton<T>::getInstance()
{
	static T instance;
	return &instance;
}

#endif

二、让某个类成为一个单例类

class Test : public singleton<Test> 
{
public:
   void foo(){} 
};

三、参考文献

《c++ template》

  博文一

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值