KrisLibrary  1.0.0
SmartPointer.h
1 #ifndef UTILS_SMART_POINTER_H
2 #define UTILS_SMART_POINTER_H
3 
4 #include <stdlib.h>
5 #include <KrisLibrary/errors.h>
6 
11 template <class T>
13 {
14 public:
15  inline SmartPointer(T* ptr = 0);
16  inline SmartPointer(const SmartPointer<T>& other);
17  inline ~SmartPointer();
18  const SmartPointer<T>& operator =(const SmartPointer<T>& rhs);
19  inline bool isNull() const { return (ptr == NULL); }
20  inline operator const T* () const { return ptr; }
21  inline operator T* () { return ptr; }
22  inline T* operator ->() { return ptr; }
23  inline const T* operator ->() const { return ptr; }
24  inline T& operator *() { return *ptr; }
25  inline const T& operator *() const { return *ptr; }
26  inline bool isNonUnique() const;
27  inline int getRefCount() const;
28 
29 protected:
30  T* ptr;
31  int* refCount;
32 };
33 
34 template <class T>
35 inline SmartPointer<T>::SmartPointer(T* _ptr)
36  : ptr(_ptr), refCount(NULL)
37 {
38  if (ptr) {
39  refCount = new int;
40  Assert(refCount != NULL);
41  *refCount = 1;
42  }
43 }
44 
45 template <class T>
47  : ptr(other.ptr), refCount(other.refCount)
48 {
49  if (refCount != NULL)
50  ++(*refCount);
51 }
52 
53 template <class T>
55 {
56  if (refCount != NULL && --(*refCount) == 0) {
57  delete ptr;
58  ptr = NULL;
59  delete refCount;
60  refCount = NULL;
61  }
62 }
63 
64 template <class T>
65 inline bool SmartPointer<T>::isNonUnique() const {
66  return refCount == NULL ? false : *refCount != 1;
67 }
68 
69 template <class T>
70 inline int SmartPointer<T>::getRefCount() const {
71  return refCount == NULL ? 0 : *refCount;
72 }
73 
74 template <class T>
76  if (ptr != rhs.ptr) {
77  if (refCount != NULL && --(*refCount) == 0) {
78  delete ptr;
79  delete refCount;
80  }
81  ptr = rhs.ptr;
82  refCount = rhs.refCount;
83  if (refCount != NULL)
84  ++(*refCount);
85  }
86  return *this;
87 }
88 
89 #endif
90 
A smart pointer class. Performs automatic reference counting.
Definition: SmartPointer.h:12