RefCountedPointer.h

Go to the documentation of this file.
00001 
00004 /*   after N.M. Josuttis, The C++ Standard Library, Addison Wesley, 
00005    Reading, 1999, p. 222 ff.  */
00006 /* Copyright 1999 by Addison Wesley Longman, Inc. 
00007    and Nicolai M. Josuttis.  All rights reserved. */
00008 
00009 /* The reference counted pointer must be a return from new */
00010 
00011 #ifndef _RefCountedPointer_h
00012 #define _RefCountedPointer_h
00013 
00014 namespace BSUtilities {
00015 
00016 template <class T> class RefCountedPointer
00017 {
00018     private:
00019 
00020       T *pointer;
00021 
00022       long *reference_count;
00023 
00024     public:
00025 
00026       explicit RefCountedPointer (T *p = 0) 
00027         : pointer (p), reference_count (new long (1))
00028         {}
00029 
00030       RefCountedPointer (const RefCountedPointer<T> &p) throw ()
00031         : pointer (p.pointer), reference_count (p.reference_count)
00032         {++*reference_count;}
00033 
00034       ~RefCountedPointer () throw ()
00035         {dispose ();}
00036 
00037       RefCountedPointer<T> & operator= (const RefCountedPointer<T> &p)
00038         throw ()
00039         { 
00040           if (this != &p)
00041           {
00042             dispose ();
00043 
00044             pointer = p.pointer;
00045 
00046             reference_count = p.reference_count;
00047 
00048             ++*reference_count;
00049           }
00050 
00051           return *this;
00052         }
00053 
00054       T & operator* () const throw ()
00055         {return *pointer;}
00056 
00057       T * operator-> () const throw ()
00058         {return pointer;}
00059 
00060     private:
00061 
00062       void dispose ()
00063       {
00064         if (--*reference_count == 0)
00065         {
00066           delete reference_count;
00067 
00068           delete pointer;
00069         }
00070       }
00071   };
00072 
00073 }
00074 #endif /* _RefCountedPointer_h */

Generated on Sun Jul 26 16:51:58 2009 for BSUtilities by  doxygen 1.5.3