Libical API Documentation  3.0
icptrholder_cxx.h
Go to the documentation of this file.
1 
42 #ifndef ICPTRHOLDER_CXX_H
43 #define ICPTRHOLDER_CXX_H
44 
45 #include <cassert>
46 
47 template < class T > class ICPointerHolder
48 {
49 public:
51  : ptr(0)
52  {
53  }
54 
55  ICPointerHolder(T *p)
56  : ptr(p)
57  {
58  }
59 
60  // copy constructor to support assignment
62  : ptr(ip.ptr)
63  {
64  // We need to transfer ownership of ptr to this object by setting
65  // ip's ptr to null. Otherwise, ptr will de deleted twice.
66  // const ugliness requires us to do the const_cast.
67  ICPointerHolder *ipp = const_cast < ICPointerHolder * >(&ip);
68 
69  ipp->ptr = 0;
70  };
71 
73  {
74  release();
75  }
76 
77  ICPointerHolder &operator=(T *p)
78  {
79  this->release();
80  ptr = p;
81  return *this;
82  }
83 
84  ICPointerHolder &operator=(ICPointerHolder &p)
85  {
86  this->release();
87  ptr = p.ptr; // this transfer ownership of the pointer
88  p.ptr = 0; // set it to null so the pointer won't get delete twice.
89  return *this;
90  }
91 
92  bool operator!=(T *p)
93  {
94  return (ptr != p);
95  }
96 
97  bool operator==(T *p)
98  {
99  return (ptr == p);
100  }
101 
102  operator T *() const
103  {
104  return ptr;
105  }
106 
107  T *operator->() const
108  {
109  assert(ptr);
110  return ptr;
111  }
112 
113  T &operator*()
114  {
115  assert(ptr);
116  return *ptr;
117  }
118 
119 private:
120  void release()
121  {
122  if (ptr != 0) {
123  ptr->detach();
124  delete ptr;
125 
126  ptr = 0;
127  }
128  }
129 
130  T *ptr;
131 };
132 
133 #endif
Definition: icptrholder_cxx.h:48