00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #ifndef _SALHELPER_SINGLETONREF_HXX_
00021 #define _SALHELPER_SINGLETONREF_HXX_
00022
00023 #include <osl/mutex.hxx>
00024 #include "rtl/instance.hxx"
00025 #include "osl/diagnose.h"
00026 #include "osl/getglobalmutex.hxx"
00027
00028
00029 namespace salhelper{
00030
00031
00064 template< class SingletonClass >
00065 class SingletonRef
00066 {
00067
00068
00069
00070 private :
00071
00073 static SingletonClass* m_pInstance;
00074
00076 static sal_Int32 m_nRef;
00077
00078
00079
00080
00081 public :
00082
00083
00084
00092 SingletonRef()
00093 {
00094
00095 ::osl::MutexGuard aLock(SingletonRef::ownStaticLock());
00096
00097
00098
00099 ++m_nRef;
00100 if (m_nRef == 1)
00101 m_pInstance = new SingletonClass();
00102
00103 OSL_ENSURE(m_nRef>0 && m_pInstance, "Race? Ref count of singleton >0, but instance is NULL!");
00104
00105 }
00106
00107
00108
00116 ~SingletonRef()
00117 {
00118
00119 ::osl::MutexGuard aLock(SingletonRef::ownStaticLock());
00120
00121
00122
00123 --m_nRef;
00124 if (m_nRef == 0)
00125 {
00126 delete m_pInstance;
00127 m_pInstance = 0;
00128 }
00129
00130 }
00131
00132
00133
00136 SingletonClass* operator->() const
00137 {
00138
00139 ::osl::MutexGuard aLock(SingletonRef::ownStaticLock());
00140 return m_pInstance;
00141
00142 }
00143
00144
00145
00148 SingletonClass& operator*() const
00149 {
00150
00151 ::osl::MutexGuard aLock(SingletonRef::ownStaticLock());
00152 return *m_pInstance;
00153
00154 }
00155
00156
00157
00158
00159 private :
00160
00161
00162
00169 struct SingletonLockInit
00170 {
00171 ::osl::Mutex* operator()()
00172 {
00173 static ::osl::Mutex aInstance;
00174 return &aInstance;
00175 }
00176 };
00177
00178 ::osl::Mutex& ownStaticLock() const
00179 {
00180 return *rtl_Instance< ::osl::Mutex,
00181 SingletonLockInit,
00182 ::osl::MutexGuard,
00183 ::osl::GetGlobalMutex >::create(SingletonLockInit(), ::osl::GetGlobalMutex());
00184 }
00185 };
00186
00187 template< class SingletonClass >
00188 SingletonClass* SingletonRef< SingletonClass >::m_pInstance = 0;
00189
00190 template< class SingletonClass >
00191 sal_Int32 SingletonRef< SingletonClass >::m_nRef = 0;
00192
00193 }
00194
00195 #endif // _SALHELPER_SINGLETONREF_HXX_
00196
00197