#ifndef __libeast_smart_ptr_h__ #define __libeast_smart_ptr_h__ // Base class for all objects with reference counting class RefCntObject { public: RefCntObject(): my_refcnt(0) {} virtual ~RefCntObject() {} // TODO: make these two functions accessible only to RefCntPointer void add_ref() {my_refcnt++;} bool sub_ref() {return --my_refcnt <= 0;} private: int my_refcnt; }; // A pointer that automatically handles reference counting template class SmartPtr { public: // Construct from normal pointer; default to NULL SmartPtr(T* ptr = NULL): my_ptr(ptr) {add_ref();} // Construct from another smart pointer SmartPtr(const SmartPtr& p): my_ptr(p) {add_ref();} // Destructor ~SmartPtr() {sub_ref();} // Assignment operators SmartPtr& operator= (const SmartPtr& rhs) { return *this = rhs; } SmartPtr& operator= (T* rhs) { if (my_ptr != rhs) { sub_ref(); my_ptr = rhs; add_ref(); } return *this; } // Dereferencing operator T& operator* () const {return *my_ptr;} // Member access operator T* operator-> () const {return my_ptr;} // Conversion operators operator T* () const {return my_ptr;} operator const T* () const {return my_ptr;} // Boolean test for NULL operator bool () const {return my_ptr != NULL;} // TODO: consider removing this // Address-of pointer (may cause memory leaks if pointer is modified) T** operator& () {return &my_ptr;} private: void add_ref() { if (my_ptr == NULL) return; my_ptr->add_ref(); } void sub_ref() { if (my_ptr == NULL) return; if (my_ptr->sub_ref()) { delete my_ptr; my_ptr = NULL; } } T* my_ptr; }; #endif