DGtal  0.6.devel
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
CountedPtr.h
1 
17 #pragma once
18 
33 #if defined(CountedPtr_RECURSES)
34 #error Recursive header files inclusion detected in CountedPtr.h
35 #else // defined(CountedPtr_RECURSES)
36 
37 #define CountedPtr_RECURSES
38 
39 #if !defined CountedPtr_h
40 
41 #define CountedPtr_h
42 
44 // Inclusions
45 #include <iostream>
46 #include "DGtal/base/Common.h"
48 
49 namespace DGtal
50 {
51 
53  // template class CountedPtr
60  template <typename T>
61  class CountedPtr
62  {
63  // ----------------------- Standard services ------------------------------
64  public:
65 
66  typedef T element_type;
67 
68  explicit CountedPtr(T* p = 0) // allocate a new counter
69  : myCounter(0) { if (p) myCounter = new counter(p);}
71  {release();}
72  CountedPtr(const CountedPtr& r) throw()
73  {acquire(r.myCounter);}
75  {
76  if (this != &r) {
77  release();
78  acquire(r.myCounter);
79  }
80  return *this;
81  }
82 
83  T& operator*() const throw() {return *myCounter->ptr;}
84  T* operator->() const throw() {return myCounter->ptr;}
85  T* get() const throw() {return myCounter ? myCounter->ptr : 0;}
86  bool unique() const throw()
87  {return (myCounter ? myCounter->count == 1 : true);}
88 
92  unsigned int count() const {return myCounter->count;}
93 private:
94 
95  struct counter {
96  counter(T* p = 0, unsigned c = 1) : ptr(p), count(c) {}
97  T* ptr;
98  unsigned count;
99  }* myCounter;
100 
101  void acquire(counter* c) throw()
102  { // increment the count
103  myCounter = c;
104  if (c) ++c->count;
105  }
106 
107  void release()
108  { // decrement the count, delete if it is 0
109  if (myCounter) {
110  if (--myCounter->count == 0) {
111  delete myCounter->ptr;
112  delete myCounter;
113  }
114  myCounter = 0;
115  }
116  }
117 
118 
119  // ----------------------- Interface --------------------------------------
120  public:
121 
126  void selfDisplay ( std::ostream & out ) const;
127 
132  bool isValid() const;
133 
134  // ------------------------- Protected Datas ------------------------------
135  private:
136  // ------------------------- Private Datas --------------------------------
137  private:
138 
139  // ------------------------- Hidden services ------------------------------
140  protected:
141 
142 
143  // ------------------------- Internals ------------------------------------
144  private:
145 
146  }; // end of class CountedPtr
147 
148 
155  template <typename T>
156  std::ostream&
157  operator<< ( std::ostream & out, const CountedPtr<T> & object );
158 
159 } // namespace DGtal
160 
161 
163 // Includes inline functions.
164 #include "DGtal/base/CountedPtr.ih"
165 
166 // //
168 
169 #endif // !defined CountedPtr_h
170 
171 #undef CountedPtr_RECURSES
172 #endif // else defined(CountedPtr_RECURSES)