1 | #ifndef _OS_SMART_POINTER_H |
2 | #define _OS_SMART_POINTER_H |
3 | |
4 | #include "os_object_base.h" |
5 | |
6 | namespace os { |
7 | |
8 | template<class T> |
9 | struct smart_ptr { |
10 | smart_ptr() : pointer(nullptr) {} |
11 | |
12 | explicit smart_ptr(T *&p) : pointer(p) { |
13 | if (pointer) { |
14 | _retain(pointer); |
15 | } |
16 | } |
17 | |
18 | smart_ptr(smart_ptr const &rhs) : pointer(rhs.pointer) { |
19 | if (pointer) { |
20 | _retain(pointer); |
21 | } |
22 | } |
23 | |
24 | smart_ptr & operator=(T *&rhs) { |
25 | smart_ptr(rhs).swap(*this); |
26 | return *this; |
27 | } |
28 | |
29 | smart_ptr & operator=(smart_ptr &rhs) { |
30 | smart_ptr(rhs).swap(*this); |
31 | return *this; |
32 | } |
33 | |
34 | ~smart_ptr() { |
35 | if (pointer) { |
36 | _release(pointer); |
37 | } |
38 | } |
39 | |
40 | void reset() { |
41 | smart_ptr().swap(*this); |
42 | } |
43 | |
44 | T *get() const { |
45 | return pointer; |
46 | } |
47 | |
48 | T ** get_for_out_param() { |
49 | reset(); |
50 | return &pointer; |
51 | } |
52 | |
53 | T * operator->() const { |
54 | return pointer; |
55 | } |
56 | |
57 | explicit |
58 | operator bool() const { |
59 | return pointer != nullptr; |
60 | } |
61 | |
62 | inline void |
63 | swap(smart_ptr &p) { |
64 | T *temp = pointer; |
65 | pointer = p.pointer; |
66 | p.pointer = temp; |
67 | } |
68 | |
69 | static inline void |
70 | _retain(T *obj) { |
71 | obj->retain(); |
72 | } |
73 | |
74 | static inline void |
75 | _release(T *obj) { |
76 | obj->release(); |
77 | } |
78 | |
79 | static inline T * |
80 | _alloc() { |
81 | return new T; |
82 | } |
83 | |
84 | T *pointer; |
85 | }; |
86 | } // namespace os |
87 | |
88 | #endif /* _OS_SMART_POINTER_H */ |
89 | |