ksharedptr.h
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 #ifndef KSharedPTR_H
00019 #define KSharedPTR_H
00020
00039 class KShared {
00040 public:
00045 KShared() : count(0) { }
00046
00051 KShared( const KShared & ) : count(0) { }
00052
00056 KShared &operator=(const KShared & ) { return *this; }
00057
00061 void _KShared_ref() const { count++; }
00062
00067 void _KShared_unref() const { if (!--count) delete this; }
00068
00074 int _KShared_count() const { return count; }
00075
00076 protected:
00077 virtual ~KShared() { }
00078 private:
00079 mutable int count;
00080 };
00081
00095 template< class T >
00096 struct KSharedPtr
00097 {
00098 public:
00102 KSharedPtr()
00103 : ptr(0) { }
00108 KSharedPtr( T* t )
00109 : ptr(t) { if ( ptr ) ptr->_KShared_ref(); }
00110
00115 KSharedPtr( const KSharedPtr& p )
00116 : ptr(p.ptr) { if ( ptr ) ptr->_KShared_ref(); }
00117
00122 ~KSharedPtr() { if ( ptr ) ptr->_KShared_unref(); }
00123
00124 KSharedPtr<T>& operator= ( const KSharedPtr<T>& p ) {
00125 if ( ptr == p.ptr ) return *this;
00126 if ( ptr ) ptr->_KShared_unref();
00127 ptr = p.ptr;
00128 if ( ptr ) ptr->_KShared_ref();
00129 return *this;
00130 }
00131 KSharedPtr<T>& operator= ( T* p ) {
00132 if ( ptr == p ) return *this;
00133 if ( ptr ) ptr->_KShared_unref();
00134 ptr = p;
00135 if ( ptr ) ptr->_KShared_ref();
00136 return *this;
00137 }
00138 bool operator== ( const KSharedPtr<T>& p ) const { return ( ptr == p.ptr ); }
00139 bool operator!= ( const KSharedPtr<T>& p ) const { return ( ptr != p.ptr ); }
00140 bool operator== ( const T* p ) const { return ( ptr == p ); }
00141 bool operator!= ( const T* p ) const { return ( ptr != p ); }
00142 bool operator!() const { return ( ptr == 0 ); }
00143 operator T*() const { return ptr; }
00144
00149 T* data() { return ptr; }
00150
00155 const T* data() const { return ptr; }
00156
00157 const T& operator*() const { return *ptr; }
00158 T& operator*() { return *ptr; }
00159 const T* operator->() const { return ptr; }
00160 T* operator->() { return ptr; }
00161
00166 int count() const { return ptr->_KShared_count(); }
00167 private:
00168 T* ptr;
00169 };
00170
00171 #endif
This file is part of the documentation for kdelibs Version 3.1.4.