DynObject

Files CCore/inc/DynObject.h CCore/src/DynObject.cpp

DynObject is a smart pointer with exclusive ownership and constant propagation. It can be used to create an object dynamically. The object is destroyed when the pointer gets out of the scope.

New()/Delete() with the DefaultHeapAlloc are used to create and destroy the object. So you don't have to derive the object type from the MemBase. Any type can be used, the only assumption is that the object destructor is nothrow.


template <class T>
class DynObject
 {
   T *ptr;
   
  public: 
   
   // constructors
   
   DynObject() noexcept : ptr(0) {}
   
   explicit DynObject(NothingType) : ptr(New<T>(DefaultHeapAlloc())) {}
   
   template <class ... SS>
   explicit DynObject(SS && ... ss) : ptr(New<T>(DefaultHeapAlloc(), std::forward<SS>(ss)... )) {}
   
   ~DynObject();

Default constructor creates the null pointer. It points to no object.

NothingType-constructor creates the pointer to the object, constructed using it's default constructor.

   
   // no copy
   
   DynObject(const DynObject<T> &obj) = delete ;
   
   DynObject<T> & operator = (const DynObject<T> &obj) = delete ;
   
   // moving
   
   DynObject(DynObject<T> &&obj);
   
   DynObject<T> & operator = (DynObject<T> &&obj);

DynObject is not copyable, but movable using the C++ move.

   
   // methods
   
   void create(NothingType);
   
   template <class ... SS>
   void create(SS && ... ss);
   
   void destroy();

For an existing pointer you can recreate the object using the method create() (the previous object, if any, is destroyed) or destroy it using the method destroy(). The method destroy() sets the pointer to the null state. The method create() preserves the pointer state, if the object creation ends with the throwing of an exception.

   
   // object pointer, const enforcement
   
   const T * operator + () const { return ptr; }
   
   bool operator ! () const { return !ptr; }
   
   T * getPtr() { return ptr; }
   
   const T * getPtr() const { return ptr; }
   
   const T * getPtr_const() const { return ptr; }
   
   T & operator * () { return *ptr; }
   
   const T & operator * () const { return *ptr; }
   
   T * operator -> () { return ptr; }
   
   const T * operator -> () const { return ptr; }

The usual set of methods can be used to access the object. The difference with the Object Pointer Interface is that the constantness is propagated from the pointer to the object.

   
   // object swap/move
   
   void objSwap(DynObject<T> &obj);
   
   explicit DynObject(ToMoveCtor<DynObject<T> > obj);
   
   DynObject<T> * objMove(Place<void> place);
 };

DynObject is swappable and CCore-movable.