1 //===--------------------------- Refcount.h ------------------------------===// 2 // 3 // SPIR Tools 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===---------------------------------------------------------------------===// 9 /* 10 * Contributed by: Intel Corporation 11 */ 12 13 #ifndef __REF_COUNT_H__ 14 #define __REF_COUNT_H__ 15 16 #include <assert.h> 17 18 namespace SPIR { 19 20 template <typename T> 21 class RefCount{ 22 public: RefCount()23 RefCount(): m_refCount(0), m_ptr(0) { 24 } 25 RefCount(T * ptr)26 RefCount(T* ptr): m_ptr(ptr) { 27 m_refCount = new int(1); 28 } 29 RefCount(const RefCount<T> & other)30 RefCount(const RefCount<T>& other) { 31 cpy(other); 32 } 33 ~RefCount()34 ~RefCount() { 35 if (m_refCount) 36 dispose(); 37 } 38 39 RefCount& operator=(const RefCount<T>& other) { 40 if(this == &other) 41 return *this; 42 if (m_refCount) 43 dispose(); 44 cpy(other); 45 return *this; 46 } 47 init(T * ptr)48 void init(T* ptr) { 49 assert(!m_ptr && "overrunning non NULL pointer"); 50 assert(!m_refCount && "overrunning non NULL pointer"); 51 m_refCount = new int(1); 52 m_ptr = ptr; 53 } 54 isNull()55 bool isNull() const { 56 return (!m_ptr); 57 } 58 59 // Pointer access 60 const T& operator*() const{ 61 sanity(); 62 return *m_ptr; 63 } 64 65 T& operator*() { 66 sanity(); 67 return *m_ptr; 68 } 69 70 operator T*() { 71 return m_ptr; 72 } 73 74 operator const T*() const{ 75 return m_ptr; 76 } 77 78 T* operator->() { 79 return m_ptr; 80 } 81 82 const T* operator->() const{ 83 return m_ptr; 84 } 85 private: sanity()86 void sanity() const{ 87 assert(m_ptr && "NULL pointer"); 88 assert(m_refCount && "NULL ref counter"); 89 assert(*m_refCount && "zero ref counter"); 90 } 91 cpy(const RefCount<T> & other)92 void cpy(const RefCount<T>& other) { 93 m_refCount = other.m_refCount; 94 m_ptr = other.m_ptr; 95 if (m_refCount) ++*m_refCount; 96 } 97 dispose()98 void dispose() { 99 sanity(); 100 if (0 == --*m_refCount) { 101 delete m_refCount; 102 delete m_ptr; 103 m_ptr = 0; 104 m_refCount = 0; 105 } 106 } 107 108 int* m_refCount; 109 T* m_ptr; 110 };// End RefCount 111 112 } // End SPIR namespace 113 114 #endif//__REF_COUNT_H__ 115