码迷,mamicode.com
首页 > 编程语言 > 详细

一个基于C++11的单例模板类

时间:2018-08-16 10:37:41      阅读:400      评论:0      收藏:0      [点我收藏+]

标签:col   std   call   oid   clu   ptr   lag   void   c++   

 1 #ifndef _SINGLETON_H_
 2 #define _SINGLETON_H_
 3 
 4 #include <mutex>
 5 #include <memory>
 6 
 7 template<typename T>
 8 class Singleton {
 9 public:
10   template <typename... ArgTypes>
11   static T* getInstance(ArgTypes... args) {
12     static std::once_flag of;
13     std::call_once(of, init(std::forward<Args>(args)...));
14 
15     return instance_.get();
16   }
17 private:
18   Singleton() = delete;
19   ~Singleton() = delete;
20   Singleton(const Singleton&) = delete;
21   Singleton(Singleton&&) = delete;
22   Singleton& operator=(const Singleton&) = delete;
23   Singleton& operator=(Singleton&&) = delete;
24 
25   template <typename... ArgTypes>
26   static void init(ArgTypes... args) {
27     instance_.reset(new T(std::forward<ArgTypes>(args)...));
28   }
29 
30   static std::unique_ptr<T> instance_;
31 };
32 
33 template<class T> 
34 std::unique_ptr<T> Singleton<T>::instance_ = nullptr;
35 
36 #endif

 

一个基于C++11的单例模板类

标签:col   std   call   oid   clu   ptr   lag   void   c++   

原文地址:https://www.cnblogs.com/CodeComposer/p/9485037.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!