1 /* $Id$ */ |
|
2 |
|
3 /** @file autoptr.hpp */ |
|
4 |
|
5 #ifndef AUTOPTR_HPP |
|
6 #define AUTOPTR_HPP |
|
7 |
|
8 /** AutoPtrT - kind of smart pointer that ensures the owned object gets |
|
9 * deleted when its pointer goes out of scope. |
|
10 * It is non-invasive smart pointer (no reference counter). |
|
11 * When copied, the copy takes ownership of underlying object |
|
12 * and original becomes NULL! |
|
13 * Can be used also for polymorphic data types (interfaces). |
|
14 */ |
|
15 template <class T> |
|
16 class AutoPtrT { |
|
17 public: |
|
18 typedef T obj_t; |
|
19 |
|
20 protected: |
|
21 mutable T* m_p; ///< points to the data |
|
22 |
|
23 public: |
|
24 FORCEINLINE AutoPtrT() |
|
25 : m_p(NULL) |
|
26 {}; |
|
27 |
|
28 FORCEINLINE AutoPtrT(const AutoPtrT<T>& src) |
|
29 : m_p(src.m_p) |
|
30 { |
|
31 if (m_p != NULL) src.m_p = NULL; |
|
32 }; |
|
33 |
|
34 FORCEINLINE AutoPtrT(T *p) |
|
35 : m_p(p) |
|
36 {} |
|
37 |
|
38 FORCEINLINE ~AutoPtrT() |
|
39 { |
|
40 if (m_p != NULL) { |
|
41 T *p = m_p; |
|
42 m_p = NULL; |
|
43 delete p; |
|
44 } |
|
45 } |
|
46 |
|
47 /** give-up ownership and NULLify the raw pointer */ |
|
48 FORCEINLINE T* Detach() |
|
49 { |
|
50 T* p = m_p; |
|
51 m_p = NULL; |
|
52 return p; |
|
53 } |
|
54 |
|
55 /** raw-pointer cast operator (read only) */ |
|
56 FORCEINLINE operator const T* () const |
|
57 { |
|
58 return m_p; |
|
59 } |
|
60 |
|
61 /** raw-pointer cast operator */ |
|
62 FORCEINLINE operator T* () |
|
63 { |
|
64 return m_p; |
|
65 } |
|
66 |
|
67 /** dereference operator (read only) */ |
|
68 FORCEINLINE const T* operator -> () const |
|
69 { |
|
70 assert(m_p != NULL); |
|
71 return m_p; |
|
72 } |
|
73 |
|
74 /** dereference operator (read / write) */ |
|
75 FORCEINLINE T* operator -> () |
|
76 { |
|
77 assert(m_p != NULL); |
|
78 return m_p; |
|
79 } |
|
80 |
|
81 /** assignment operator */ |
|
82 FORCEINLINE AutoPtrT& operator = (const AutoPtrT& src) |
|
83 { |
|
84 /* Save original pointer and replace it with the given one to avoid recursive calls. */ |
|
85 T* p = m_p; |
|
86 m_p = src.m_p; |
|
87 |
|
88 if (m_p != NULL) src.m_p = NULL; |
|
89 |
|
90 if (p != NULL) { |
|
91 /* Now we can safely delete the old one. */ |
|
92 delete p; |
|
93 } |
|
94 return *this; |
|
95 } |
|
96 |
|
97 /** forwarding 'lower than' operator to the underlaying items */ |
|
98 FORCEINLINE bool operator < (const AutoPtrT& other) const |
|
99 { |
|
100 assert(m_p != NULL); |
|
101 assert(other.m_p != NULL); |
|
102 return (*m_p) < (*other.m_p); |
|
103 } |
|
104 }; |
|
105 |
|
106 #endif /* AUTOPTR_HPP */ |
|