more convenient and flexible implementation of dptr;
[web/konrad/chester.git] / dptr_shared.h
diff --git a/dptr_shared.h b/dptr_shared.h
new file mode 100644 (file)
index 0000000..7e73853
--- /dev/null
@@ -0,0 +1,62 @@
+//d-ptr header
+//
+// (c) Konrad Rosenbaum, 2010-2011
+// Copying and distribution of this file, with or without modification,
+// are permitted in any medium without royalty provided the copyright
+// notice and this notice are preserved.  This file is offered as-is,
+// without any warranty.
+
+#include "dptr_base.h"
+
+
+#ifndef DPTR_SHAREDCLASS_H
+#define DPTR_SHAREDCLASS_H
+//hide the namespace
+/// \cond never
+namespace Chester_0_1{
+/// \endcond
+
+/** \brief Base class of shared d-pointers.
+
+Use in conjunction with DECLARE_SHARED_DPTR and DEFINE_SHARED_DPTR */
+class SharedDPtr
+{
+       private:
+               int cnt;
+       public:
+               ///instantiates a shared d-pointer
+               SharedDPtr(){cnt=1;}
+               ///deletes a shared d-pointer
+               virtual ~SharedDPtr(){}
+               ///called by the wrapper to attach to a new instance
+               virtual void attach(){cnt++;}
+               ///called by the wrapper to detach from an instance
+               virtual void detach(){cnt--;if(cnt==0)delete this;}
+};
+
+//hide the namespace
+/// \cond never
+};
+using namespace Chester_0_1;
+/// \endcond
+
+#endif
+
+#ifdef DEFINE_SHARED_DPTR
+#undef DEFINE_SHARED_DPTR
+#endif
+
+/** \brief Defines the methods of the shared d-pointer wrapper.
+
+This implements the shared version of the d-pointer wrapper.
+To be used in implementation where the actual d-pointer class is implemented.
+
+\param Class the base class within which the d-pointer was declared*/
+#define DEFINE_SHARED_DPTR(Class) \
+ Class::DPrivate::DPrivate(){d=new Class::Private;}\
+ Class::DPrivate::DPrivate(const DPrivate&dp){d=dp.d;d->attach();}\
+ Class::DPrivate::~DPrivate(){d->detach();}\
+ Class::DPrivate Class::DPrivate::clone()const{DPrivate r;*(r.d)=*d;return r;}\
+ Class::DPrivate& Class::DPrivate::operator=(const DPrivate&dp)\
+ {d->detach();d=dp.d;d->attach();return *this;}
+