proj home

Files   Classes   Functions   Hierarchy  

singleton.h

Go to the documentation of this file.
00001 #ifndef SINGLETON_H
00002 #define SINGLETON_H
00003 
00004 #include <cassert>
00005 using namespace std;
00006 
00010 template<typename T>
00011 class Singleton
00012 {
00013 public:
00014 
00015   static T * ptr;
00016 
00017   Singleton(T* ptr_)
00018     { ptr=ptr_; }
00019 };
00020 
00021 
00048 template< class T>
00049 class SingletonPtr
00050 {
00051   static T*  ptr;
00052 public:
00053   
00055   static int count;
00056 
00058   typedef enum memoryRelease { never=0, nonarray, array };
00059 
00061   explicit SingletonPtr(T* app);
00063   explicit SingletonPtr(T* app, SingletonPtr<T>::memoryRelease m);
00064 
00066   SingletonPtr();
00068   ~SingletonPtr();
00069 
00071   T* operator->();
00073   T& operator()();
00074 
00075 private:
00076    static memoryRelease memorystate;
00077 };
00078 
00079 
00080 
00081 
00082 // ---------------------------------------------------------
00083 // Implementation
00084 
00085 template<typename T>
00086 T * Singleton<T>::ptr = 0;
00087 
00088 template<class T>
00089 T* SingletonPtr<T>::ptr = 0;
00090 template<class T>
00091 int SingletonPtr<T>::count = 0;
00092 
00093 template<class T>
00094 typename SingletonPtr<T>::memoryRelease 
00095 SingletonPtr<T>::memorystate = SingletonPtr<T>::never;
00096 
00097 
00098 template<class T>
00099 inline SingletonPtr<T>::SingletonPtr(T* app)
00100 {
00101    assert(ptr==0);
00102 
00103   ptr = app;
00104   count = 1;
00105   memorystate = never;
00106 }
00107 
00108 
00109 template<class T>
00110 inline SingletonPtr<T>::SingletonPtr
00111   (T* app, SingletonPtr<T>::memoryRelease m)
00112 {
00113 
00114   assert(ptr==0);
00115 
00116   memorystate = m;
00117 
00118   ptr = app;
00119   count = 1;
00120 }
00121 
00122 
00123 template<class T>
00124 inline SingletonPtr<T>::SingletonPtr()
00125 {
00126   assert(ptr!=0);
00127   assert( (count>=1) || (memorystate==never));
00128 
00129   ++count;
00130 }
00131 
00132 template<class T>
00133 inline T* SingletonPtr<T>::operator->()
00134 {
00135   assert(ptr!=0);
00136 
00137   return ptr;
00138 }
00139 
00140 template<class T>
00141 inline T& SingletonPtr<T>::operator()()
00142 {
00143   assert(ptr!=0);
00144 
00145   return *ptr;
00146 }
00147 
00148 template<class T>
00149 inline SingletonPtr<T>::~SingletonPtr()
00150 {
00151   --count;
00152   if (count<=0)
00153   {
00154 
00155 assert(count==0);
00156 
00157     switch(memorystate)
00158     {
00159       case never: break;
00160       case array: delete[] ptr; break;
00161       case nonarray: delete ptr; break;
00162     }
00163 
00164     if (memorystate!=never)
00165       ptr=0;
00166   }
00167 }
00168 
00169 
00170 #endif
00171 
00172 
00173 

Generated on Fri Mar 4 00:49:29 2011 for Chelton Evans Source by  doxygen 1.5.8