pointer.hpp
Go to the documentation of this file.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
00029
00030 template <class T> class CountedPtr
00031 {
00032 public:
00033 typedef T *pointer;
00034 typedef T &reference;
00035
00036 explicit CountedPtr( pointer pPtr = 0 ): m_pCounter( 0 )
00037 {
00038 if( pPtr ) m_pCounter = new Counter( pPtr );
00039 }
00040
00041 ~CountedPtr() { release(); }
00042
00043 CountedPtr( const CountedPtr &rPtr ) { acquire( rPtr.m_pCounter ); }
00044
00045 CountedPtr &operator=( const CountedPtr &rPtr )
00046 {
00047 if( this != &rPtr )
00048 {
00049 release();
00050 acquire( rPtr.m_pCounter );
00051 }
00052 return *this;
00053 }
00054
00055
00056 reference operator*() const { return *m_pCounter->m_pPtr; }
00057 pointer operator->() const { return m_pCounter->m_pPtr; }
00058
00059 pointer get() const { return m_pCounter ? m_pCounter->m_pPtr : 0; }
00060
00061 bool unique() const
00062 {
00063 return ( m_pCounter ? m_pCounter->m_count == 1 : true );
00064 }
00065
00066 private:
00067 struct Counter
00068 {
00069 Counter( pointer pPtr = 0, unsigned int c = 1 )
00070 : m_pPtr( pPtr ), m_count( c ) { }
00071 pointer m_pPtr;
00072 unsigned int m_count;
00073 } *m_pCounter;
00074
00075 void acquire( Counter* pCount )
00076 {
00077 m_pCounter = pCount;
00078 if( pCount ) ++pCount->m_count;
00079 }
00080
00081 void release()
00082 {
00083 if( m_pCounter )
00084 {
00085 if( --m_pCounter->m_count == 0 )
00086 {
00087 delete m_pCounter->m_pPtr;
00088 delete m_pCounter;
00089 }
00090 m_pCounter = 0;
00091 }
00092 }
00093 };
00094
00095
00096 #endif