Tianchi  v0.0.2 build 20130701
C++ library for Qt with VC & mingW
tcsingleton.hpp
浏览该文件的文档.
1 // **************************************************************************
2 // Tianchi C++ library for Qt (open source)
3 // 天池共享源码库
4 // 版权所有 (C) 天池共享源码库开发组
5 // 授权协议:请阅读天池共享源码库附带的授权协议
6 // **************************************************************************
7 // 文档说明:用指针实现的单例模式的模版类
8 // ==========================================================================
9 // 开发日志:
10 // 日期 人员 说明
11 // --------------------------------------------------------------------------
12 // 2013.05.25 cnhemiya@gmail.com 建立
13 //
14 // ==========================================================================
16 // ==========================================================================
37 
38 #ifndef TIANCHI_TCSINGLETON_HPP
39 #define TIANCHI_TCSINGLETON_HPP
40 
41 #include <cassert>
42 
43 template<typename T>
45 {
46  typedef TcSingleton<T> this_type;
47 
48 public:
51  {
52  if (m_count == 0)
53  m_pointer = new T;
54 
55  ++m_count;
56  }
57 
60  {
61  ++m_count;
62  }
63 
66  {
67  --m_count;
68 
69  if (m_count == 0)
70  {
71  delete m_pointer;
72  m_pointer = 0;
73  }
74  }
75 
77  inline T * get() const
78  {
79  assert(m_pointer != 0);
80  return m_pointer;
81  }
82 
84  inline const T & operator *() const
85  {
86  assert(m_pointer != 0);
87  return *m_pointer;
88  }
89 
91  inline T * operator ->() const
92  {
93  assert(m_pointer != 0);
94  return m_pointer;
95  }
96 
98  inline this_type & operator =(const this_type &)
99  {
100  return *this;
101  }
102 
103 private:
104  static T *m_pointer;
105  static int m_count;
106 };
107 
109 #define TC_SINGLETON_INIT(__t) \
110 template<> int TcSingleton< __t >::m_count = 0; \
111 template<> __t * TcSingleton< __t >::m_pointer = 0;
112 
113 
114 #endif // TIANCHI_TCSINGLETON_HPP