ANTLR Support Libraries 2.7.1+
RefCount.hpp
Go to the documentation of this file.
1 #ifndef INC_RefCount_hpp__
2 #define INC_RefCount_hpp__
3 /* ANTLR Translator Generator
4  * Project led by Terence Parr at http://www.jGuru.com
5  * Software rights: http://www.antlr.org/license.html
6  *
7  * $Id: //depot/code/org.antlr/release/antlr-2.7.7/lib/cpp/antlr/RefCount.hpp#2 $
8  */
9 
10 #include <antlr/config.hpp>
11 
12 #ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
13 namespace antlr {
14 #endif
15 
16 template<class T>
18 private:
19  struct Ref {
20  T* const ptr;
21  unsigned int count;
22 
23  Ref(T* p) : ptr(p), count(1) {}
24  ~Ref() {delete ptr;}
25  Ref* increment() {++count;return this;}
26  bool decrement() {return (--count==0);}
27  private:
28  Ref(const Ref&);
29  Ref& operator=(const Ref&);
30  }* ref;
31 
32 public:
33  explicit RefCount(T* p = 0)
34  : ref(p ? new Ref(p) : 0)
35  {
36  }
37  RefCount(const RefCount<T>& other)
38  : ref(other.ref ? other.ref->increment() : 0)
39  {
40  }
42  {
43  if (ref && ref->decrement())
44  delete ref;
45  }
47  {
48  Ref* tmp = other.ref ? other.ref->increment() : 0;
49  if (ref && ref->decrement())
50  delete ref;
51  ref = tmp;
52  return *this;
53  }
54 
55  operator T* () const
56  {
57  return ref ? ref->ptr : 0;
58  }
59 
60  T* operator->() const
61  {
62  return ref ? ref->ptr : 0;
63  }
64 
65  T* get() const
66  {
67  return ref ? ref->ptr : 0;
68  }
69 
70  template<class newType> operator RefCount<newType>()
71  {
72  return RefCount<newType>(ref);
73  }
74 };
75 
76 #ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
77 }
78 #endif
79 
80 #endif //INC_RefCount_hpp__
Definition: ANTLRException.hpp:15
unsigned int count
Definition: RefCount.hpp:21
RefCount(T *p=0)
Definition: RefCount.hpp:33
#define ANTLR_API
Definition: config.hpp:22
RefCount(const RefCount< T > &other)
Definition: RefCount.hpp:37
T * operator->() const
Definition: RefCount.hpp:60
Definition: RefCount.hpp:19
RefCount< T > & operator=(const RefCount< T > &other)
Definition: RefCount.hpp:46
T *const ptr
Definition: RefCount.hpp:20
Definition: RefCount.hpp:17
~Ref()
Definition: RefCount.hpp:24
struct RefCount::Ref * ref
Ref(T *p)
Definition: RefCount.hpp:23
bool decrement()
Definition: RefCount.hpp:26
~RefCount()
Definition: RefCount.hpp:41
Ref * increment()
Definition: RefCount.hpp:25