GDCM  2.0.18
gdcmSmartPointer.h
Go to the documentation of this file.
00001 /*=========================================================================
00002 
00003   Program: GDCM (Grassroots DICOM). A DICOM library
00004 
00005   Copyright (c) 2006-2011 Mathieu Malaterre
00006   All rights reserved.
00007   See Copyright.txt or http://gdcm.sourceforge.net/Copyright.html for details.
00008 
00009      This software is distributed WITHOUT ANY WARRANTY; without even
00010      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
00011      PURPOSE.  See the above copyright notice for more information.
00012 
00013 =========================================================================*/
00014 #ifndef GDCMSMARTPOINTER_H
00015 #define GDCMSMARTPOINTER_H
00016 
00017 #include "gdcmObject.h"
00018 
00019 namespace gdcm
00020 {
00038 template<class ObjectType>
00039 class SmartPointer
00040 {
00041 public:
00042   SmartPointer():Pointer(0) {}
00043   SmartPointer(const SmartPointer<ObjectType>& p):Pointer(p.Pointer)
00044     { Register(); }
00045   SmartPointer(ObjectType* p):Pointer(p)
00046     { Register(); }
00047   SmartPointer(ObjectType const & p)
00048     {
00049     Pointer = const_cast<ObjectType*>(&p);
00050     Register();
00051     }
00052   ~SmartPointer() {
00053     UnRegister();
00054     Pointer = 0;
00055   }
00056 
00058   ObjectType *operator -> () const
00059     { return Pointer; }
00060 
00061   ObjectType& operator * () const
00062     { return *Pointer; }
00063 
00065   operator ObjectType * () const
00066     { return Pointer; }
00067 
00069   SmartPointer &operator = (SmartPointer const &r)
00070     { return operator = (r.Pointer); }
00071 
00073   SmartPointer &operator = (ObjectType *r)
00074     {
00075     // http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.22
00076     // DO NOT CHANGE THE ORDER OF THESE STATEMENTS!
00077     // (This order properly handles self-assignment)
00078     // (This order also properly handles recursion, e.g., if a ObjectType contains SmartPointer<ObjectType>s)
00079     if( Pointer != r )
00080       {
00081       ObjectType* old = Pointer;
00082       Pointer = r;
00083       Register();
00084       if ( old ) { old->UnRegister(); }
00085       }
00086     return *this;
00087     }
00088 
00089   SmartPointer &operator = (ObjectType const &r)
00090     {
00091     ObjectType* tmp = const_cast<ObjectType*>(&r);
00092     return operator = (tmp);
00093     }
00094 
00096   ObjectType *GetPointer() const
00097     { return Pointer; }
00098 
00099 private:
00100   void Register()
00101     {
00102     if(Pointer) Pointer->Register();
00103     }
00104 
00105   void UnRegister()
00106     {
00107     if(Pointer) Pointer->UnRegister();
00108     }
00109 
00110   ObjectType* Pointer;
00111 };
00112 
00113 } // end namespace gdcm
00114 
00115 #endif //GDCMSMARTPOINTER_H

Generated on Tue Dec 6 2011 07:25:32 for GDCM by doxygen 1.7.5.1
SourceForge.net Logo