class RefCounted { protected: RefCounted(){ m_ref_count = 0; } virtual ~RefCounted(){} public: void incRef() { ++m_ref_count; } void desRef() { if (--m_ref_count == 0) { delete this; } } private: int m_ref_count; }; template<typename T> class RefPtr { public: RefPtr(){ m_ptr = 0; } template<typename U> RefPtr(U* ptr) { m_ptr = ptr; if (m_ptr) { m_ptr->incRef(); } } template<typename U> RefPtr(const RefPtr<U>& ptr) { m_ptr = ptr.getRefPtr(); if (m_ptr) { m_ptr->incRef(); } } ~RefPtr() { if (m_ptr) { m_ptr->desRef(); m_ptr = 0; } } template<typename U> RefPtr<T>& operator=(U* ptr) { if (m_ptr != ptr) { if (m_ptr) { m_ptr->desRef(); } m_ptr = ptr; if (m_ptr) { m_ptr->incRef(); } } return *this; } template<typename U> RefPtr<T>& operator=(const RefPtr<U>& ptr) { if (m_ptr != ptr.getRefPtr()) { if (m_ptr) { m_ptr->desRef(); } m_ptr = ptr.getRefPtr(); if (m_ptr) { m_ptr->incRef(); } } return *this; } T* operator->() const { return m_ptr; } T& operator*() const { return *m_ptr; } operator bool() const { return (m_ptr != 0); } T* getRefPtr() const { return m_ptr; } private: T* m_ptr; }; template<typename T, typename U> bool operator==(const RefPtr<T>& a, const RefPtr<U>& b) { return (a.getRefPtr() == b.getRefPtr()); } template<typename T, typename U> bool operator==(const RefPtr<T>& a, const U* b) { return (a.getRefPtr() == b); } template<typename T, typename U> bool operator==(const U* a, const RefPtr<T>& b) { return (a == b.getRefPtr()); } template<typename T, typename U> bool operator!=(const RefPtr<T>& a, const RefPtr<U>& b) { return (a.getRefPtr() != b.getRefPtr()); } template<typename T, typename U> bool operator!=(const RefPtr<T>& a, const U* b) { return (a.getRefPtr() != b); } template<typename T, typename U> bool operator!=(const U* a, const RefPtr<T>& b) { return (a != b.getRefPtr()); }
时间: 2024-11-05 13:49:26