CppUnit project page CppUnit home page

scopedptr.h

Go to the documentation of this file.
00001 #ifndef CPPTL_SCOPEDPTR_H_INCLUDED
00002 # define CPPTL_SCOPEDPTR_H_INCLUDED
00003 
00004 # include <cpptl/config.h>
00005 
00006 namespace CppTL {
00007 
00008 template<class PointeeType>
00009 class ScopedPtr : public NonCopyable
00010 {
00011 public:
00012    typedef ScopedPtr<PointeeType> SelfType;
00013 
00014    ScopedPtr( PointeeType *p = 0 )
00015       : p_( p )
00016    {
00017    }
00018 
00019    ~ScopedPtr()
00020    {
00021       checkedDelete( p_ );
00022    }
00023 
00024    void swap( SelfType &other )
00025    {
00026       CppTL::swap( p_, other.p_ );
00027    }
00028 
00029    void reset( PointeeType *p = 0 )
00030    {
00031       SelfType temp(p);
00032       swap( temp );
00033    }
00034 
00035    PointeeType *get() const
00036    {
00037       return p_;
00038    }
00039 
00040    PointeeType &operator *() const
00041    {
00042       CPPTL_ASSERT_MESSAGE( p_ != 0, "Attempted to use null pointer" );
00043       return *p_;
00044    }
00045 
00046    PointeeType *operator ->() const
00047    {
00048       CPPTL_ASSERT_MESSAGE( p_ != 0, "Attempted to use null pointer" );
00049       return p_;
00050    }
00051 
00052    operator bool() const
00053    {
00054       return p_ != 0;
00055    }
00056 
00057    bool operator !() const
00058    {
00059       return p_ == 0;
00060    }
00061 
00062 private:
00063    PointeeType *p_;
00064 };
00065 
00066 
00067 template<class PointeeType>
00068 class ScopedArray : public NonCopyable
00069 {
00070 public:
00071    typedef ScopedArray<PointeeType> SelfType;
00072 
00073    ScopedArray( PointeeType *p = 0 )
00074       : p_( p )
00075    {
00076    }
00077 
00078    ~ScopedArray()
00079    {
00080       checkedArrayDelete( p_ );
00081    }
00082 
00083    void swap( SelfType &other )
00084    {
00085       CppTL::swap( p_, other.p_ );
00086    }
00087 
00088    void reset( PointeeType *p = 0 )
00089    {
00090       SelfType temp(p);
00091       swap( temp );
00092    }
00093 
00094    PointeeType *get() const
00095    {
00096       return p_;
00097    }
00098 
00099    PointeeType &operator *() const
00100    {
00101       CPPTL_ASSERT_MESSAGE( p_ != 0, "Attempted to use null pointer" );
00102       return *p_;
00103    }
00104 
00105    PointeeType *operator ->() const
00106    {
00107       CPPTL_ASSERT_MESSAGE( p_ != 0, "Attempted to use null pointer" );
00108       return p_;
00109    }
00110 
00111    operator bool() const
00112    {
00113       return p_ != 0;
00114    }
00115 
00116    bool operator !() const
00117    {
00118       return p_ == 0;
00119    }
00120 
00121 private:
00122    PointeeType *p_;
00123 };
00124 
00125 
00126 } // namespace CppTL
00127 
00128 
00129 
00130 #endif // CPPTL_SCOPEDPTR_H_INCLUDED
00131 

SourceForge Logo hosts this site. Send comments to:
CppUnit Developers