1 template <typename T>
2 class Pointer {
3 protected:
4 unsigned int* ptrCount;
5 T* ptrObject;
6
7 void ptrDetach(void)
8 {
9 if (ptrCount && --(*ptrCount)==0) {
10 delete ptrObject;
11 delete ptrCount;
12 }
13 ptrObject = NULL;
14 ptrCount = NULL;
15 }
16
17 public:
18 explicit Pointer(T* ptr = NULL) : ptrObject(ptr)
19 {
20 ptrCount = new unsigned int;
21 *ptrCount = 1;
22 }
23
24 Pointer(const Pointer<T>& ref)
25 {
26 ptrObject = ref.ptrObject;
27 ptrCount = ref.ptrCount;
28 ++(*ptrCount);
29 }
30 inline virtual ~Pointer()
31 { ptrDetach(); }
32
33 Pointer& operator = (const Pointer<T>& ref)
34 {
35 if (this!=&ref) {
36 ptrDetach();
37 ptrObject = ref.ptrObject;
38 ptrCount = ref.ptrCount;
39 ++(*ptrCount);
40 }
41 return *this;
42 }
43
44 inline T& operator*() const
45 {
46 return *ptrObject;
47 }
48 inline T* getObject() const
49 {
50 return ptrObject;
51 }
52 inline T* operator ->()const
53 {
54 return ptrObject;
55 }
56 inline bool operator!() const
57 {
58 return (*ptrCount==1);
59 }
60 inline int operator++() const
61 {
62 return ++(*ptrCount);
63 }
64 int operator--() const
65 {
66 if (*ptrCount==1) {
67 delete this;
68 return 0;
69 }
70 return --(*ptrCount);
71 }
72 }