If you want to be sure you don''t get it wrong, and also want
to be exception-safe, it''s good to have a "smart pointer"
that takes care of adding and subtracting reference counts.
template <typename T>class RefPtr { private: T *m_pObject; public: RefPtr(T *pObject) : m_pObject(pObject) { pObject->AddRef(); } RefPtr(const RefPtr &Other) : m_pObject(Other.m_pObject) { m_pObject->AddRef(); } ~RefPtr(void) // Release() returns true if ref count drops to 0 { if (m_pObject->Release()) delete m_pObject; } const RefPtr &operator=(const RefPtr &Other) { if (m_pObject->Release()) delete m_pObject; m_pObject = Other.m_pObject; m_pObject->AddRef(); return *this; } // end if T *operator->(void) const { return m_pObject; } T &operator*(void) const { return *m_pObject; } };// end
This class is by no means complete. I leave that as an
exercise to the reader (i.e. you) to fix the holes.
(Hint: null-pointer (I mean 0) and self-assignment...etc)
Kami no Itte ga ore ni zettai naru!