CARMA C++
AutoFreedMallocPtr.h
1 #ifndef CARMA_UTIL_AUTO_FREED_MALLOC_PTR_H
2 #define CARMA_UTIL_AUTO_FREED_MALLOC_PTR_H
3 
4 #include <cstdlib>
5 
7 
8 
9 namespace carma {
10 namespace util {
11 
12 
15 
16 template < typename T >
18  public:
19  explicit AutoFreedMallocPtr( );
20 
21  explicit AutoFreedMallocPtr( T * tPtr );
22 
24 
26 
27  template < typename S >
29  tPtr_( rhs.release() )
30  {
31  }
32 
33  AutoFreedMallocPtr & operator=( AutoFreedMallocPtr & rhs );
34 
35  template < typename S >
37  operator=( AutoFreedMallocPtr< S > & rhs )
38  {
39  reset( rhs.release() );
40  return *this;
41  }
42 
43  T & operator*( ) const;
44 
45  T * operator->( ) const;
46 
47  T * get( ) const;
48 
49  T * release( );
50 
51  void reset( T * tPtr = 0 );
52 
53  template < typename S >
54  operator AutoFreedMallocPtr< S >( )
55  {
56  return AutoFreedMallocPtr< S >( this->release() );
57  }
58 
59  private:
60  T * tPtr_;
61 };
62 
63 
64 } // namespace carma::util
65 } // namespace carma
66 
67 
68 // ******* Below here is simply implementation *******
69 
70 template < typename T >
72 tPtr_( 0 )
73 {
74 }
75 
76 
77 template < typename T >
79 tPtr_( tPtr )
80 {
81 }
82 
83 
84 template < typename T >
86 tPtr_( rhs.release() )
87 {
88 }
89 
90 
91 template < typename T >
93 try {
94  if ( tPtr_ != 0 )
95  ::free( tPtr_ );
96 } catch ( ... ) {
97  // Just stifle any exception
98 
99  return;
100 }
101 
102 
103 template < typename T >
105 carma::util::AutoFreedMallocPtr< T >::operator=( AutoFreedMallocPtr & rhs )
106 {
107  reset( rhs.release() );
108 
109  return *this;
110 }
111 
112 
113 template < typename T >
114 T &
116 {
117  if ( tPtr_ == 0 )
118  throw CARMA_ERROR( "AutoFreedMallocPtr pointer is NULL" );
119 
120  return *tPtr_;
121 }
122 
123 
124 template < typename T >
125 T *
127 {
128  if ( tPtr_ == 0 )
129  throw CARMA_ERROR( "AutoFreedMallocPtr pointer is NULL" );
130 
131  return tPtr_;
132 }
133 
134 
135 template < typename T >
136 T *
138 {
139  return tPtr_;
140 }
141 
142 
143 template < typename T >
144 T *
146 {
147  T * result = tPtr_;
148  tPtr_ = 0;
149 
150  return result;
151 }
152 
153 
154 template < typename T >
155 void
157 {
158  if ( tPtr != tPtr_ ) {
159  if ( tPtr_ != 0 )
160  ::free( tPtr_ );
161 
162  tPtr_ = tPtr;
163  }
164 }
165 
166 
167 #endif
Exception class for errors.
AutoFreedMallocPtr&lt; T &gt; works like ::std::auto_ptr&lt; T &gt; except that the pointer is ::free&#39;ed (if it is no...
#define CARMA_ERROR(y)
Trick to get the file name and line number passed to the exception handler.