c++11 单例模式
2015-12-01 00:37
561 查看
#ifndef __SINGLETON_H__ #define __SINGLETON_H__ #include <thread> #include <memory> #include <mutex> #include <exception> template<typename T> class Singleton { public: Singleton() = default; ~Singleton() = default; Singleton(const Singleton &) = delete; Singleton(Singleton &&) = delete; Singleton &operator=(const Singleton &) = delete; Singleton &operator=(Singleton &&) = delete; template<typename ...Args> static void make_shared_instance(Args&&...args) { if (instance) { throw std::runtime_error("instance is already make."); } instance= std::make_shared<T>(std::forward<Args>(args)...); } template<typename ...Args> static std::shared_ptr<T> makeInstance(Args&& ... args) { std::call_once(flag, make_shared_instance<Args...>, std::forward<Args>(args)...); return instance; } template<typename ...Args> static std::shared_ptr<T> Instance() { if (instance) { return instance; } throw std::runtime_error("instance is not make."); } private: static std::once_flag flag; static std::shared_ptr<T> instance; }; template<typename T> std::once_flag Singleton<T>::flag; template<typename T> std::shared_ptr<T> Singleton<T>::instance; #endif//__SINGLETON_H__
相关文章推荐
- C++学习笔记2
- 嵌入式寄存器操作-----C语言位操作的学习
- C语言URL编解码
- 先来先服务算法实现(c语言)
- leetcode笔记:Construct Binary Tree from Inorder and Postorder Traversal
- 【C语言】测试系统各数据类型大小代码
- The C++ Standard Library: RTTI(Run-Time Type Identification,运行时类型识别)
- leetcode笔记:Construct Binary Tree from Preorder and Inorder Traversal
- 用C++模拟操作系统进程调度的几种算法
- leetcode 258 Add Digits C++
- 【C语言提高13】二级指针
- 冒泡排序
- 字符串函数汇总
- 【iOS学习笔记】c语言问题
- STL运用的C++技术(2)——模板特化
- 设计模式C++实现(9)——享元模式
- leetcode 292 Nim Game C++
- STL运用的C++技术(1)——成员模板
- C++对象的初始化
- 学习C++需要注意的问题