00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #ifndef POINTER_HPP
00026 #define POINTER_HPP
00027
00028
00030 template <class T> class CountedPtr
00031 {
00032 public:
00033 explicit CountedPtr( T *pPtr = 0 ): m_pCounter( 0 )
00034 {
00035 if( pPtr ) m_pCounter = new Counter( pPtr );
00036 }
00037
00038 ~CountedPtr() { release(); }
00039
00040 CountedPtr(const CountedPtr &rPtr ) { acquire( rPtr.m_pCounter ); }
00041
00042 CountedPtr &operator=( const CountedPtr &rPtr )
00043 {
00044 if( this != &rPtr )
00045 {
00046 release();
00047 acquire( rPtr.m_pCounter );
00048 }
00049 return *this;
00050 }
00051
00052 T &operator*() const { return *m_pCounter->m_pPtr; }
00053
00054 T *operator->() const {return m_pCounter->m_pPtr; }
00055
00056 T *get() const { return m_pCounter ? m_pCounter->m_pPtr : 0; }
00057
00058 bool unique() const
00059 {
00060 return ( m_pCounter ? m_pCounter->m_count == 1 : true );
00061 }
00062
00063 private:
00064 struct Counter
00065 {
00066 Counter( T* pPtr = 0, unsigned int c = 1 ):
00067 m_pPtr( pPtr ), m_count( c ) {}
00068 T* m_pPtr;
00069 unsigned int m_count;
00070 } *m_pCounter;
00071
00072 void acquire( Counter* pCount )
00073 {
00074 m_pCounter = pCount;
00075 if( pCount ) ++pCount->m_count;
00076 }
00077
00078 void release()
00079 {
00080 if( m_pCounter )
00081 {
00082 if( --m_pCounter->m_count == 0 )
00083 {
00084 delete m_pCounter->m_pPtr;
00085 delete m_pCounter;
00086 }
00087 m_pCounter = 0;
00088 }
00089 }
00090 };
00091
00092
00093 #endif