aboutsummaryrefslogtreecommitdiff
path: root/src/sptr.h
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/sptr.h147
1 files changed, 147 insertions, 0 deletions
diff --git a/src/sptr.h b/src/sptr.h
new file mode 100644
index 0000000..faa8524
--- /dev/null
+++ b/src/sptr.h
@@ -0,0 +1,147 @@
1#ifndef SPTR_H
2#define SPTR_H
3
4#include <stdint.h>
5#include <stdio.h>
6
7namespace Bu
8{
9 template<typename T> class SPtr;
10 template< typename Tb, typename Ta > SPtr<Tb> SPtrCast( SPtr<Ta> src );
11
12 template<typename T>
13 class SPtr
14 {
15 template<typename Tb, typename Ta>
16 friend SPtr<Tb> SPtrCast( SPtr<Ta> pt );
17 public:
18 SPtr() :
19 pRefCnt( NULL ),
20 pData( NULL )
21 {
22 }
23
24 ~SPtr()
25 {
26 decCount();
27 }
28
29 SPtr( const SPtr<T> &src ) :
30 pRefCnt( src.pRefCnt ),
31 pData( src.pData )
32 {
33 if( pRefCnt )
34 (*pRefCnt) += 1;
35 }
36
37 SPtr( T *pSrc ) :
38 pRefCnt( NULL ),
39 pData( pSrc )
40 {
41 if( pData )
42 {
43 pRefCnt = new int32_t;
44 (*pRefCnt) = 1;
45 }
46 }
47
48 int32_t count() const
49 {
50 return *pRefCnt;
51 }
52
53 const T *operator->() const
54 {
55 return pData;
56 }
57
58 const T &operator*() const
59 {
60 return *pData;
61 }
62
63 T *operator->()
64 {
65 return pData;
66 }
67
68 T &operator*()
69 {
70 return *pData;
71 }
72
73 SPtr<T> operator=( const SPtr<T> &src )
74 {
75 decCount();
76 pRefCnt = src.pRefCnt;
77 pData = src.pData;
78 if( pRefCnt )
79 (*pRefCnt) += 1;
80
81 return *this;
82 }
83
84 const SPtr<T> operator=( const SPtr<T> &src ) const
85 {
86 decCount();
87 pRefCnt = src.pRefCnt;
88 pData = src.pData;
89 if( pRefCnt )
90 (*pRefCnt) += 1;
91
92 return *this;
93 }
94
95 bool operator==( const SPtr<T> &src ) const
96 {
97 return pData == src.pData;
98 }
99
100 bool operator==( const T *src ) const
101 {
102 return pData == src;
103 }
104
105 operator bool() const
106 {
107 return pRefCnt != NULL;
108 }
109
110 bool isSet() const
111 {
112 return pRefCnt != NULL;
113 }
114
115 private:
116 void decCount() const
117 {
118 if( pRefCnt )
119 {
120 (*pRefCnt) -= 1;
121 //printf("Decrementing ref-count to %d\n", *pRefCnt );
122 if( (*pRefCnt) == 0 )
123 {
124 delete pRefCnt;
125 delete pData;
126 pRefCnt = NULL;
127 pData = NULL;
128 }
129 }
130 }
131
132 mutable int32_t *pRefCnt;
133 mutable T *pData;
134 };
135
136 template< typename Tb, typename Ta > SPtr<Tb> SPtrCast( SPtr<Ta> src )
137 {
138 SPtr<Tb> ret;
139 ret.pRefCnt = src.pRefCnt;
140 ret.pData = dynamic_cast<Tb *>(src.pData);
141 if( ret.pRefCnt )
142 (*(ret.pRefCnt)) += 1;
143 return ret;
144 }
145}
146
147#endif