00001 #ifndef SMART_POINTER_H 00002 #define SMART_POINTER_H 00003 00004 template<class ITEM> 00005 class SmartPointer 00006 { 00007 protected: 00008 ITEM* impl; 00009 00010 public: 00011 SmartPointer() throw () : impl(0) {} 00012 00013 SmartPointer(const SmartPointer& sp) throw () 00014 { 00015 if (sp.impl) 00016 sp.impl->ref(); 00017 impl = sp.impl; 00018 } 00019 00020 SmartPointer(ITEM* otherimpl) throw () 00021 { 00022 if (otherimpl) 00023 otherimpl->ref(); 00024 impl = otherimpl; 00025 } 00026 00027 ~SmartPointer() throw () 00028 { 00029 if (impl && impl->unref()) 00030 delete impl; 00031 } 00032 00033 SmartPointer& operator=(const SmartPointer& sp) throw () 00034 { 00035 if (sp.impl) 00036 sp.impl->ref(); // Do it early to correctly handle the case of x = x; 00037 if (impl && impl->unref()) 00038 delete impl; 00039 impl = sp.impl; 00040 return *this; 00041 } 00042 00043 operator bool() const throw () { return impl != 0; } 00044 }; 00045 00046 class SmartPointerItem 00047 { 00048 protected: 00049 int _ref; 00050 00051 public: 00052 SmartPointerItem() throw () : _ref(0) {} 00053 00055 void ref() throw () { ++_ref; } 00056 00059 bool unref() throw () { return --_ref == 0; } 00060 }; 00061 00062 // vim:set ts=3 sw=3: 00063 #endif