00001 #ifndef _theplu_yat_utility_smart_ptr_
00002 #define _theplu_yat_utility_smart_ptr_
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025 #include "yat_assert.h"
00026
00027 namespace theplu {
00028 namespace yat {
00029 namespace utility {
00030
00039 template<typename T>
00040 class SmartPtr
00041 {
00042 public:
00065 explicit SmartPtr(T* p=NULL, bool owner=true)
00066 : pointee_(p)
00067 {
00068 if (owner)
00069 ref_count_ = new unsigned int(1);
00070 else
00071 ref_count_ = NULL;
00072 }
00073
00077 SmartPtr(const SmartPtr& other)
00078 : pointee_(other.pointee_), ref_count_(other.ref_count_)
00079 {
00080 if (ref_count_)
00081 ++(*ref_count_);
00082 }
00083
00089 virtual ~SmartPtr()
00090 {
00091 detach();
00092 }
00093
00099 SmartPtr& operator=(const SmartPtr& rhs)
00100 {
00101 if (pointee_!=rhs.pointee_){
00102 detach();
00103 pointee_ = rhs.pointee_;
00104 ref_count_= rhs.ref_count_;
00105 if (ref_count_)
00106 ++(*ref_count_);
00107 }
00108 return *this;
00109 }
00110
00114 T* operator->(void) const
00115 {
00116 return pointee_;
00117 }
00118
00122 T& operator*(void) const
00123 {
00124 return *pointee_;
00125 }
00126
00127 private:
00128 T* pointee_;
00129 unsigned int* ref_count_;
00130
00131 void detach(void)
00132 {
00133 if (ref_count_)
00134 if (!--(*ref_count_))
00135 delete pointee_;
00136 }
00137 };
00138
00139
00140
00141
00142
00143
00144 }}}
00145
00146 #endif