From 22cff2c24e05d57d3d9cdc7ca00151460310825b Mon Sep 17 00:00:00 2001 From: Guido Kanschat Date: Fri, 4 Sep 1998 11:43:46 +0000 Subject: [PATCH] SmartPointer in own file git-svn-id: https://svn.dealii.org/trunk@559 0785d39b-7218-0410-832d-ea1e28bc413d --- deal.II/base/include/base/smartpointer.h | 109 +++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 deal.II/base/include/base/smartpointer.h diff --git a/deal.II/base/include/base/smartpointer.h b/deal.II/base/include/base/smartpointer.h new file mode 100644 index 0000000000..d057467128 --- /dev/null +++ b/deal.II/base/include/base/smartpointer.h @@ -0,0 +1,109 @@ +/*---------------------------- smartpointer.h ---------------------------*/ +/* $Id$ */ +#ifndef __smartpointer_H +#define __smartpointer_H +/*---------------------------- smartpointer.h ---------------------------*/ + +#ifndef #ifndef __subscriptor_H +#include +#endif + +/** + * Smart pointers avoid destruction of an object in use. They can be used just + * like a pointer (i.e. using the #*# and #-># operators and through casting) + * but make sure that the object pointed to is not deleted in the course of + * use of the pointer by signalling the pointee its use. + * + * Objects pointed to should inherit #Subscriptor# or must implement + * the same functionality. Null pointers are an exception from this + * rule and are allowed, too. + * + * #SmartPointer# does NOT implement any memory handling! Especially, + * deleting a #SmartPointer# does not delete the object. Writing + *
+ * SmartPointer t = new T;
+ * 
+ * is a sure way to program a memory leak! The secure version is + *
+ * T* p = new T;
+ * {
+ *   SmartPointer t = p;
+ *   ...
+ * }
+ * delete p;
+ * 
*/ +template +class SmartPointer +{ + T* t; + + public: + /** + * Constructor taking a normal pointer. */ + SmartPointer(T* tt) : + t(tt) + { + t->subscribe(); + } + + /** + * Standard constructor for null pointer. + */ + SmartPointer() : + t(0) + {} + + /** + * Destructor, removing the subscription. + */ + ~SmartPointer() + { + if (t) + t->unsubscribe(); + } + /** + * Assignment operator. Change of + * subscription is necessary. + */ + SmartPointer& operator=(T* tt) + { + if (t) + t->unsubscribe(); + t = tt; + if (tt) + tt->subscribe(); + return *this; + } + + + /** + * Conversion to normal pointer. + */ + operator T* () const + { + return t; + } + + /** + * Dereferencing operator. + */ + T& operator* () const + { + return *t; + } + + /** + * Dereferencing operator. + */ + T* operator -> () const + { + return t; + } +}; + + + +/*---------------------------- smartpointer.h ---------------------------*/ +/* end of #ifndef __smartpointer_H */ +#endif +/*---------------------------- smartpointer.h ---------------------------*/ -- 2.39.5