单例——在应用程序中某个类的实例只有一个,以便做全局访问点,这样可以协调系统的整体行为。也就是说提供访问某一资源(硬件设备、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》