PolyBoRi
CExtrusivePtr.h
Go to the documentation of this file.
1 // -*- c++ -*-
2 //*****************************************************************************
16 //*****************************************************************************
17 
18 #ifndef polybori_common_CExtrusivePtr_h_
19 #define polybori_common_CExtrusivePtr_h_
20 
21 // include basic definitions
22 #include <polybori/pbori_defs.h>
23 #include <algorithm> // std::swap
24 
26 
43 template <class DataType, class ValueType>
45 
47  typedef CExtrusivePtr self;
48 
49 public:
50 
52  typedef DataType data_type;
53 
55  typedef ValueType value_type;
56 
58  CExtrusivePtr(const data_type& data, value_type* ptr):
59  m_data(data), p_ptr(ptr) { lock(); }
60 
62  CExtrusivePtr(const self& rhs):
63  m_data(rhs.m_data), p_ptr(rhs.p_ptr) { lock(); }
64 
66  m_data(), p_ptr(NULL) { }
67 
69  ~CExtrusivePtr() { release(); }
70 
72  self& operator=(const self& rhs) {
73  self(rhs).swap(*this);
74  return *this;
75  }
76 
78  const data_type& data() const { return m_data; }
79 
81  value_type* get() const {
82  return p_ptr;
83  }
84 
86  const value_type & operator*() const {
87  PBORI_ASSERT(p_ptr != NULL);
88  return *p_ptr;
89  }
90 
92  value_type & operator*() {
93  PBORI_ASSERT(p_ptr != NULL);
94  return *p_ptr;
95  }
96 
98  value_type* operator->() const {
99  PBORI_ASSERT(p_ptr != NULL);
100  return p_ptr;
101  }
102 
104  void swap(self & rhs) {
105  std::swap(m_data, rhs.m_data);
106  std::swap(p_ptr, rhs.p_ptr);
107  }
108 
109 protected:
110  void lock() {
111  extrusive_ptr_add_ref(data(), get());
112  }
113  void release() {
114  extrusive_ptr_release(data(), get());
115  }
116 
119 
121  value_type* p_ptr;
122 };
123 
125 template <class Data1, class Type1, class Data2, class Type2>
126 inline bool
128  const CExtrusivePtr<Data2, Type2> & rhs) {
129  return lhs.get() == rhs.get();
130 }
131 
133 template <class Data1, class Type1, class Data2, class Type2>
134 inline bool
136  const CExtrusivePtr<Data2, Type2> & rhs) {
137  return lhs.get() != rhs.get();
138 }
139 
141 template <class Data1, class Type1, class Type2>
142 inline bool
143 operator==(const CExtrusivePtr<Data1, Type1> & lhs, Type2 * rhs) {
144  return lhs.get() == rhs;
145 }
146 
148 template <class Data1, class Type1, class Type2>
149 inline bool
150 operator!=(const CExtrusivePtr<Data1, Type1> & lhs, Type2* rhs) {
151  return lhs.get() != rhs;
152 }
153 
155 template <class Type1, class Data2, class Type2>
156 inline bool
157 operator==(Type1* lhs, const CExtrusivePtr<Data2, Type2> & rhs) {
158  return lhs == rhs.get();
159 }
160 
162 template <class Type1, class Data2, class Type2>
163 inline bool
164 operator!=(Type1* lhs, const CExtrusivePtr<Data2, Type2> & rhs) {
165  return lhs != rhs.get();
166 }
167 
169 
170 #endif