refPtr.h
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 #ifndef EQBASE_REFPTR_H
00019 #define EQBASE_REFPTR_H
00020
00021 #include <eq/base/base.h>
00022 #include <eq/base/debug.h>
00023
00024 #include <iostream>
00025 #include <typeinfo>
00026 #include <stdlib.h>
00027
00028 namespace eq
00029 {
00030 namespace base
00031 {
00037 template<class T> class RefPtr
00038 {
00039 public:
00041 RefPtr() : _ptr( 0 ) {}
00043 RefPtr( T* const ptr ) : _ptr( ptr ) { ref(); }
00045 RefPtr( const RefPtr& from ) : _ptr( from._ptr ) { ref(); }
00047 ~RefPtr() { unref(); _ptr = 0; }
00048
00050 void ref() { if(_ptr) _ptr->ref(); }
00051
00053 void unref()
00054 {
00055 if(_ptr)
00056 {
00057 #ifndef NDEBUG
00058 const bool abondon = (_ptr->getRefCount() == 1);
00059 _ptr->unref();
00060 if( abondon )
00061 _ptr = 0;
00062 #else
00063 _ptr->unref();
00064 #endif
00065 }
00066 }
00067
00069 RefPtr& operator = ( const RefPtr& rhs )
00070 {
00071 if( _ptr == rhs._ptr )
00072 return *this;
00073
00074 T* tmp = _ptr;
00075 _ptr = rhs._ptr;
00076 ref();
00077 if( tmp ) tmp->unref();
00078 return *this;
00079 }
00080
00082 RefPtr& operator = ( T* ptr )
00083 {
00084 if( _ptr == ptr )
00085 return *this;
00086
00087 T* tmp = _ptr;
00088 _ptr = ptr;
00089 ref();
00090 if( tmp ) tmp->unref();
00091 return *this;
00092 }
00093
00095 bool operator == ( const RefPtr& rhs ) const
00096 { return ( _ptr==rhs._ptr ); }
00098 bool operator != ( const RefPtr& rhs ) const
00099 { return ( _ptr!=rhs._ptr ); }
00101 bool operator < ( const RefPtr& rhs ) const
00102 { return ( _ptr < rhs._ptr ); }
00104 bool operator > ( const RefPtr& rhs ) const
00105 { return ( _ptr > rhs._ptr ); }
00107 bool operator ! () const { return ( _ptr==0 ); }
00108
00110 bool operator == ( const T* ptr ) const { return ( _ptr==ptr ); }
00112 bool operator != ( const T* ptr ) const { return ( _ptr!=ptr ); }
00113
00115 T* operator->()
00116 { EQASSERTINFO( _ptr, typeid(*this).name( )); return _ptr; }
00118 const T* operator->() const
00119 { EQASSERTINFO( _ptr, typeid(*this).name( )); return _ptr; }
00121 T& operator*()
00122 { EQASSERTINFO( _ptr, typeid(*this).name( )); return *_ptr; }
00124 const T& operator*() const
00125 { EQASSERTINFO( _ptr, typeid(*this).name( )); return *_ptr; }
00126
00128 T* get() { return _ptr; }
00130 const T* get() const { return _ptr; }
00131
00133 bool isValid() const { return ( _ptr != 0 ); }
00134
00135 private:
00136 T* _ptr;
00137 };
00138
00140 template< class T >
00141 inline std::ostream& operator << ( std::ostream& os, const RefPtr<T>& rp )
00142 {
00143 os << "RefPtr<" << rp.get() << ">";
00144 return os;
00145 }
00146 }
00147
00148 }
00149 #endif //EQBASE_REFPTR_H