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>
17 class ANTLR_API RefCount {
18 private:
19 	struct Ref {
20 		T* const ptr;
21 		unsigned int count;
22 
Refantlr::RefCount::Ref23 		Ref(T* p) : ptr(p), count(1) {}
~Refantlr::RefCount::Ref24 		~Ref() {delete ptr;}
incrementantlr::RefCount::Ref25 		Ref* increment() {++count;return this;}
decrementantlr::RefCount::Ref26 		bool decrement() {return (--count==0);}
27 	private:
28 		Ref(const Ref&);
29 		Ref& operator=(const Ref&);
30 	}* ref;
31 
32 public:
RefCount(T * p=0)33 	explicit RefCount(T* p = 0)
34 	: ref(p ? new Ref(p) : 0)
35 	{
36 	}
RefCount(const RefCount<T> & other)37 	RefCount(const RefCount<T>& other)
38 	: ref(other.ref ? other.ref->increment() : 0)
39 	{
40 	}
~RefCount()41 	~RefCount()
42 	{
43 		if (ref && ref->decrement())
44 			delete ref;
45 	}
operator =(const RefCount<T> & other)46 	RefCount<T>& operator=(const RefCount<T>& other)
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 
operator T*() const55 	operator T* () const
56 	{
57 		return ref ? ref->ptr : 0;
58 	}
59 
operator ->() const60 	T* operator->() const
61 	{
62 		return ref ? ref->ptr : 0;
63 	}
64 
get() const65 	T* get() const
66 	{
67 		return ref ? ref->ptr : 0;
68 	}
69 
operator RefCount<newType>()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__
81