halapi
hierarchichalalignmentformatapi
 All Classes Namespaces Functions Pages
cpbroke.h
1 /*
2  * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
3  *
4  * Released under the MIT license, see LICENSE.txt
5  */
6 
7 
22 /*
23  * counted_ptr - simple reference counted pointer.
24  *
25  * The is a non-intrusive implementation that allocates an additional
26  * int and pointer for every counted object.
27  */
28 
29 #ifndef COUNTED_PTR_H
30 #define COUNTED_PTR_H
31 
32 namespace hal {
33 
34 template<typename X>
35 struct ptr_counter {
36  ptr_counter(X* p = 0, unsigned c = 1) : ptr(p), count(c) {}
37  X* ptr;
38  unsigned count;
39 };
40 
41 template <class X>
43 {
44 public:
45  template <typename XX> friend class counted_ptr;
46  typedef ptr_counter<X> counter;
47 
48  explicit counted_ptr(X* p = 0) // allocate a new counter
49  : itsCounter(0) {
50  if (p) itsCounter = new counter(p);
51  }
52 
53  ~counted_ptr() {
54  release();
55  }
56 
57  template <class Y>
58  counted_ptr(const counted_ptr<Y>& r) {
59  acquire<Y>(r.itsCounter);
60  }
61 
62  template <class Y>
63  counted_ptr& operator=(const counted_ptr<Y>& r) {
64  if (const_cast<const counted_ptr<X>*>(this) !=
65  reinterpret_cast<const counted_ptr<X>*>(
66  const_cast<const counted_ptr<Y>*>(&r)))
67  {
68  release();
69  acquire<Y>(r.itsCounter);
70  }
71  return *this;
72  }
73 
74  X& operator*() const {return *itsCounter->ptr;}
75  X* operator->() const {return itsCounter->ptr;}
76  X* get() const {return itsCounter ? itsCounter->ptr : 0;}
77  bool unique() const {
78  return (itsCounter ? itsCounter->count == 1 : true);
79  }
80 
81 private:
82 
83  counter* itsCounter;
84 
85  template <typename Y>
86  void acquire(ptr_counter<Y>* c) {
87  if (c) {
88  (void)static_cast<X*>(c->ptr);
89  itsCounter = reinterpret_cast<counter*>(c);
90  ++c->count;
91  }
92  else {
93  itsCounter = NULL;
94  }
95  }
96 
97  void release() {
98  if (itsCounter) {
99  if (--itsCounter->count == 0) {
100  delete itsCounter->ptr;
101  delete itsCounter;
102  }
103  itsCounter = 0;
104  }
105  }
106 };
107 
108 
109 }
110 #endif // COUNTED_PTR_H