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