yat
0.8.3pre
|
00001 #ifndef _theplu_yat_utility_smart_ptr_ 00002 #define _theplu_yat_utility_smart_ptr_ 00003 00004 // $Id: SmartPtr.h 2119 2009-12-12 23:11:43Z peter $ 00005 00006 /* 00007 Copyright (C) 2008 Jari Häkkinen, Peter Johansson 00008 00009 This file is part of the yat library, http://dev.thep.lu.se/yat 00010 00011 The yat library is free software; you can redistribute it and/or 00012 modify it under the terms of the GNU General Public License as 00013 published by the Free Software Foundation; either version 3 of the 00014 License, or (at your option) any later version. 00015 00016 The yat library is distributed in the hope that it will be useful, 00017 but WITHOUT ANY WARRANTY; without even the implied warranty of 00018 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 00019 General Public License for more details. 00020 00021 You should have received a copy of the GNU General Public License 00022 along with yat. If not, see <http://www.gnu.org/licenses/>. 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 }}} // of namespace utility, yat, and theplu 00145 00146 #endif