Files CCore/inc/OwnPtr.h CCore/src/OwnPtr.cpp
OwnPtr is a smart pointer with the exclusive ownership semantic.
template <class T> struct OwnAlgo { static void Destroy(T *ptr) { delete ptr; } }; template <class T,class Algo=OwnAlgo<T> > class OwnPtr : NoCopy { T *ptr; public: // constructors OwnPtr() noexcept : ptr(0) {} explicit OwnPtr(T *ptr_) : ptr(ptr_) {} ~OwnPtr() { if( ptr ) Algo::Destroy(ptr); } // std move OwnPtr(OwnPtr<T,Algo> &&obj) noexcept; OwnPtr<T,Algo> & operator = (OwnPtr<T,Algo> &&obj) noexcept; // object ptr T * operator + () const { return ptr; } bool operator ! () const { return !ptr; } T * getPtr() const { return ptr; } T & operator * () const { return *ptr; } T * operator -> () const { return ptr; } // reset void set(T *new_ptr) { if( T *old_ptr=Replace(ptr,new_ptr) ) Algo::Destroy(old_ptr); } T * detach(T *new_ptr=0) { return Replace(ptr,new_ptr); } // swap/move objects void objSwap(OwnPtr<T,Algo> &obj) { Swap(ptr,obj.ptr); } explicit OwnPtr(ToMoveCtor<OwnPtr<T,Algo> > obj); OwnPtr<T,Algo> * objMove(Place<void> place); };
OwnPtr has only one data member — pointer to the object of the type T. This pointer may be null. OwnPtr is not copyable (but has the move constructor and the move assign operator) and its destructor destroys the pointed object using the provided algorithm Algo::Destroy(). The pointer comes from the constructor argument. Using OwnPtr make sure the argument is "destroyable". By default, Algo::Destroy(ptr) is just delete ptr;, so the object must be created by the new expression.
OwnPtr is std movable. The original object is nullified during the move.
OwnPtr implements Object Pointer Interface. It also swappable and movable.
Two additional "unsafe" methods set() and detach() can be used to manipulate the internal pointer.
set() setup a new pointer and destroy the previous one. It is the same as the destructor plus the following constructor call.
detach() setup a new pointer and return the previous one.
Using the template parameter Algo you may customize the destruction process.
The typical usage of the OwnPtr is to create an object with the scope life-time duration.
class C { .... }; .... { OwnPtr<C> ptr( new C() ); .... ptr->method(); .... }
The object will be destroyed when the scope is exited by any way. This method is useful instead of creation a local variable of the type C, if the sizeof (C) is too large. You can also return an OwnPtr from a function (this is impossible with a local variable):
void func(OwnPtr<C> &ret) { OwnPtr<C> ptr( new C() ); Swap(ptr,ret); } .... OwnPtr<C> result; func(result); ....