$darkmode
Libical API Documentation 4.0 STABLE VERSION Visit the v3.0 documentation
icptrholder_cxx.hpp
Go to the documentation of this file.
1 /*
2  * SPDX-FileCopyrightText: 2001, Critical Path
3  * SPDX-License-Identifier: LGPL-2.1-only OR MPL-2.0
4  */
5 
37 #ifndef ICPTRHOLDER_CXX_H
38 #define ICPTRHOLDER_CXX_H
39 
40 #include <cassert>
41 
42 template<class T>
44 {
45 public:
47  : ptr(0)
48  {
49  }
50 
51  /* cppcheck-suppress noExplicitConstructor */
52  ICPointerHolder(T *p) // NOLINT(runtime/explicit)
53  : ptr(p)
54  {
55  }
56 
57  // copy constructor to support assignment
59  : ptr(ip.ptr)
60  {
61  // We need to transfer ownership of ptr to this object by setting
62  // ip's ptr to null. Otherwise, ptr will de deleted twice.
63  // const ugliness requires us to do the const_cast.
64  ICPointerHolder *ipp = const_cast<ICPointerHolder *>(&ip);
65 
66  ipp->ptr = 0;
67  };
68 
70  {
71  release();
72  }
73 
74  ICPointerHolder &operator=(T *p)
75  {
76  this->release();
77  ptr = p;
78  return *this;
79  }
80 
81  ICPointerHolder &operator=(ICPointerHolder &p) //NOLINT(misc-unconventional-assign-operator)
82  {
83  if (this == &p) {
84  return *this;
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  /* cppcheck-suppress constParameterPointer */
93  bool operator!=(T *p)
94  {
95  return (ptr != p);
96  }
97 
98  /* cppcheck-suppress constParameterPointer */
99  bool operator==(T *p)
100  {
101  return (ptr == p);
102  }
103 
104  operator T *() const
105  {
106  return ptr;
107  }
108 
109  T *operator->() const
110  {
111  icalassert(ptr);
112  return ptr;
113  }
114 
115  T &operator*()
116  {
117  icalassert(ptr);
118  return *ptr;
119  }
120 
121 private:
122  void release()
123  {
124  if (ptr != 0) {
125  ptr->detach();
126  delete ptr;
127 
128  ptr = 0;
129  }
130  }
131 
132  T *ptr;
133 };
134 
135 #endif