====== Smart pointer ====== ===== Description ===== Smart pointer is an abstract data type, that extend functionality for standard c++ pointers. The most import features are automatic lifetime and references management of the wrapped objects. Smart pointer automatically deletes non-referenced objects and fulfills the role of garbage collector. This is very useful for reduce memmory leaks and related bugs. ===== Source code C++ ===== #pragma once #ifndef SMARTPOINTER_H_ #define SMARTPOINTER_H_ #include "assert.h" template class SmartPointer { public: SmartPointer(); SmartPointer(T* pT); ~SmartPointer(); SmartPointer(const SmartPointer& rT); SmartPointer& operator=(const SmartPointer& rT); T* operator->(); const T* operator->() const; bool operator==(const SmartPointer& rT) const; bool operator!=(const SmartPointer& rT) const; bool Null() const {return m_pCounted == 0;} void SetNull() { UnBind(); } private: void UnBind(); template class Counted { friend class SmartPointer; private: Counted(T* pT) : Count(0), my_pT(pT) { assert(pT != 0); } ~Counted() { assert(Count == 0); delete my_pT; } unsigned GetRef() { return ++Count; } unsigned FreeRef() { assert(Count!=0); return --Count; } T* const my_pT; unsigned Count; }; Counted* m_pCounted; }; template SmartPointer::SmartPointer() : m_pCounted(0) {} template SmartPointer::SmartPointer(T* pT) { m_pCounted = new Counted(pT); m_pCounted->GetRef(); } template SmartPointer::~SmartPointer() { UnBind(); } template void SmartPointer::UnBind() { if (!Null() && m_pCounted->FreeRef() == 0) delete m_pCounted; m_pCounted = 0; } template T* SmartPointer::operator->() { return m_pCounted->my_pT; } template const T* SmartPointer::operator->() const { return m_pCounted->my_pT; } template SmartPointer::SmartPointer(const SmartPointer& rT) { m_pCounted = rT.m_pCounted; if (!Null()) m_pCounted->GetRef(); } template SmartPointer& SmartPointer::operator=(const SmartPointer& rT) { if (!rT.Null()) rT.m_pCounted->GetRef(); UnBind(); m_pCounted = rT.m_pCounted; return *this; } template bool SmartPointer::operator==(const SmartPointer& rT) const { return rT.m_pCounted->my_pT == m_pCounted->my_pT; } template bool SmartPointer::operator!=(const SmartPointer& rT) const { return !(rT == this); } #endif /* SMARTPOINTER_H_ */ ===== References ===== * [[http://en.wikipedia.org/wiki/Smart_pointer]]\\ * [[http://www.davethehat.com/articles/smartp.htm]]\\