Files CCore/inc/RefPtr.h CCore/src/RefPtr.cpp
RefPtr is an intrusive smart-pointer with the reference counting.
template <class T> struct RefAlgo { static void IncRef(T *ptr) { ptr->incRef(); } static bool DecRef(T *ptr) { return ptr->decRef(); } static void Destroy(T *ptr) { ptr->destroy(); } }; template <class T,class Algo=RefAlgo<T> > class RefPtr { T *ptr; public: // constructors explicit RefPtr(T *ptr_) : ptr(ptr_) {} // ptr_!=0 ~RefPtr(); // copying RefPtr(const RefPtr<T,Algo> &obj); RefPtr<T,Algo> & operator = (const RefPtr<T,Algo> &obj); // object ptr T * getPtr() const { return ptr; } T & operator * () const { return *ptr; } T * operator -> () const { return ptr; } // reset void set(T *new_ptr); // new_ptr!=0 // update template <class Func> void update(Func func) { ptr=func(ptr); } // swap/move objects void objSwap(RefPtr<T,Algo> &obj) { Swap(ptr,obj.ptr); } explicit RefPtr(ToMoveCtor<RefPtr<T,Algo> > obj); RefPtr<T,Algo> * objMove(Place<void> place); };
RefPtr has only one data member — non-null pointer to the object of the type T. The pointer comes from the constructor argument. RefPtr is copyable, multiple RefPtrs may point to the same object. To determine the moment the object should be destroyed the reference counting is used. It assumes, that the type T has an embedded reference counter of some nature and a family of methods to manipulate the one. The template parameter Algo allows customization of these methods. By default, to increment the reference counter the method incRef() is called, to decrement — decRef() and to destroy the object — the method destroy(). decRef() returns true, if the reference counter became zero, i.e. it's time to destroy the object. To create RefPtr a non-null pointer with reference counter 1 must be provided.
RefPtr implements the reduced Object Pointer Interface, because it always points to an object. It also swappable and movable.
Two additional "unsafe" methods set() and update() can be used to manipulate the internal pointer.
set() setup a new pointer and "decrement" the previous one. It is the same as the destructor plus the following constructor call.
update() updates the pointer by the given functor. The correctness of this operation must be ensured by the functor.
RefPtr is not intended to be used "as is". Normally it should be a part of the outer class. This class is used in the implementation of the RefArray.