summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/sptr.cpp1
-rw-r--r--src/sptr.h85
-rw-r--r--src/tests/sptr.cpp55
3 files changed, 141 insertions, 0 deletions
diff --git a/src/sptr.cpp b/src/sptr.cpp
new file mode 100644
index 0000000..7f5e894
--- /dev/null
+++ b/src/sptr.cpp
@@ -0,0 +1 @@
#include "sptr.h"
diff --git a/src/sptr.h b/src/sptr.h
new file mode 100644
index 0000000..c711a89
--- /dev/null
+++ b/src/sptr.h
@@ -0,0 +1,85 @@
1#ifndef SPTR_H
2#define SPTR_H
3
4#include <stdint.h>
5#include <stdio.h>
6
7template<typename T>
8class SPtr
9{
10public:
11 SPtr() :
12 pRefCnt( NULL ),
13 pData( NULL )
14 {
15 }
16
17 ~SPtr()
18 {
19 decCount();
20 }
21
22 SPtr( SPtr<T> &src ) :
23 pRefCnt( src.pRefCnt ),
24 pData( src.pData )
25 {
26 (*pRefCnt) += 1;
27 }
28
29 SPtr( T *pSrc ) :
30 pRefCnt( NULL ),
31 pData( pSrc )
32 {
33 pRefCnt = new uint32_t;
34 (*pRefCnt) = 1;
35 }
36
37 uint32_t count()
38 {
39 return *pRefCnt;
40 }
41
42 T *operator->() const
43 {
44 return pData;
45 }
46
47 T *operator*() const
48 {
49 return pData;
50 }
51
52 SPtr<T> operator=( const SPtr<T> &src )
53 {
54 decCount();
55 pRefCnt = src.pRefCnt;
56 pData = src.pData;
57 (*pRefCnt) += 1;
58 }
59
60 bool operator==( const SPtr<T> &src )
61 {
62 return pData == src.pData;
63 }
64
65private:
66 void decCount()
67 {
68 if( pRefCnt )
69 {
70 (*pRefCnt) -= 1;
71 if( (*pRefCnt) == 0 )
72 {
73 delete pRefCnt;
74 delete pData;
75 pRefCnt = NULL;
76 pData = NULL;
77 }
78 }
79 }
80
81 uint32_t *pRefCnt;
82 T *pData;
83};
84
85#endif
diff --git a/src/tests/sptr.cpp b/src/tests/sptr.cpp
new file mode 100644
index 0000000..38d3675
--- /dev/null
+++ b/src/tests/sptr.cpp
@@ -0,0 +1,55 @@
1#include <stdio.h>
2#include "sptr.h"
3
4class Annoy
5{
6public:
7 Annoy() : nCnt( 0 )
8 {
9 printf("Created.\n");
10 }
11
12 ~Annoy()
13 {
14 printf("Destroyed.\n");
15 }
16
17 void go()
18 {
19 printf("%d: I'm annoying.\n", ++nCnt);
20 }
21
22 int nCnt;
23};
24
25void beAnnoying( SPtr<Annoy> bob )
26{
27 printf("bob-Count: %d\n", bob.count() );
28 bob->go();
29}
30
31int main()
32{
33 SPtr<Annoy> pt( new Annoy );
34 printf("Count: %d\n", pt.count() );
35 pt->go();
36
37 {
38 SPtr<Annoy> pt2 = pt;
39 printf("Count: %d\n", pt2.count() );
40
41 pt2->go();
42
43 {
44 SPtr<Annoy> pt3( pt2 );
45 printf("Count: %d\n", pt3.count() );
46
47 pt3->go();
48
49 beAnnoying( pt3 );
50 }
51 printf("Count: %d\n", pt.count() );
52 }
53 printf("Count: %d\n", pt.count() );
54}
55