ANTLR Support Libraries 2.7.1+
antlr/RefCount.hpp
Go to the documentation of this file.
00001 #ifndef INC_RefCount_hpp__
00002 #define INC_RefCount_hpp__
00003 /* ANTLR Translator Generator
00004  * Project led by Terence Parr at http://www.jGuru.com
00005  * Software rights: http://www.antlr.org/license.html
00006  *
00007  * $Id: //depot/code/org.antlr/release/antlr-2.7.7/lib/cpp/antlr/RefCount.hpp#2 $
00008  */
00009 
00010 #include <antlr/config.hpp>
00011 
00012 #ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
00013 namespace antlr {
00014 #endif
00015 
00016 template<class T>
00017 class ANTLR_API RefCount {
00018 private:
00019    struct Ref {
00020       T* const ptr;
00021       unsigned int count;
00022 
00023       Ref(T* p) : ptr(p), count(1) {}
00024       ~Ref() {delete ptr;}
00025       Ref* increment() {++count;return this;}
00026       bool decrement() {return (--count==0);}
00027    private:
00028       Ref(const Ref&);
00029       Ref& operator=(const Ref&);
00030    }* ref;
00031 
00032 public:
00033    explicit RefCount(T* p = 0)
00034    : ref(p ? new Ref(p) : 0)
00035    {
00036    }
00037    RefCount(const RefCount<T>& other)
00038    : ref(other.ref ? other.ref->increment() : 0)
00039    {
00040    }
00041    ~RefCount()
00042    {
00043       if (ref && ref->decrement())
00044          delete ref;
00045    }
00046    RefCount<T>& operator=(const RefCount<T>& other)
00047    {
00048       Ref* tmp = other.ref ? other.ref->increment() : 0;
00049       if (ref && ref->decrement())
00050          delete ref;
00051       ref = tmp;
00052       return *this;
00053    }
00054 
00055    operator T* () const
00056    {
00057       return ref ? ref->ptr : 0;
00058    }
00059 
00060    T* operator->() const
00061    {
00062       return ref ? ref->ptr : 0;
00063    }
00064 
00065    T* get() const
00066    {
00067       return ref ? ref->ptr : 0;
00068    }
00069 
00070    template<class newType> operator RefCount<newType>()
00071    {
00072       return RefCount<newType>(ref);
00073    }
00074 };
00075 
00076 #ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
00077 }
00078 #endif
00079 
00080 #endif //INC_RefCount_hpp__
 All Classes Namespaces Files Functions Variables Typedefs Friends Defines