基于c++新标准线程安全的单例模板实现 |
您所在的位置:网站首页 › c++线程安全单例 › 基于c++新标准线程安全的单例模板实现 |
单例——在应用程序中某个类的实例只有一个,以便做全局访问点,这样可以协调系统的整体行为。也就是说提供访问某一资源(硬件设备、ini文件……)的统一接口。 在此只讨论基于c++新标准的一个线程安全实现。涉及到CRTP(Curiously Recurring Template Prattern)的使用。先看以下知识点: 1. c++新标准中指出:局部static变量的初始化是线程安全的。 2. CRTP 可以使类具备某些特性,这里利用此特性,使我们的类可以成为一个单例。(受std::enable_shared_from_this启发)。 一、基类的定义 #ifndef SINGLETON_BASE_CPP_11_H #define SINGLETON_BASE_CPP_11_H #include template class singleton { public: static T *getInstance(); virtual ~singleton(){}; protected: singleton(){}; singleton(const singleton &ref) = delete; singleton &operator=(const singleton &ref) = delete; }; template T *singleton::getInstance() { static T instance; return &instance; } #endif 二、让某个类成为一个单例类 class Test : public singleton { public: void foo(){} }; 三、参考文献《c++ template》 博文一 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |