00001 #ifndef QUICKSP_H_ 00002 #define QUICKSP_H_ 00003 00004 struct NoLock 00005 { 00006 void lock() {} 00007 void unlock() {} 00008 }; 00009 00010 // TODO: implement for threads 00011 // If implemented for threads move the instance pointer to simple_ref_ptr 00012 // so simple access isn't synchronized. 00013 struct ThreadLock 00014 { 00015 void lock() {} 00016 00017 void unlock() {} 00018 }; 00019 00020 // TODO: Get a real reference counted smart pointer in libmyth 00021 template <typename T, class Locker = NoLock> 00022 class simple_ref_ptr 00023 { 00024 public: 00025 simple_ref_ptr() : m_ref(0) 00026 { 00027 } 00028 00029 simple_ref_ptr(T *ptr) 00030 { 00031 m_ref = new ref(ptr); 00032 } 00033 00034 simple_ref_ptr(const simple_ref_ptr &rhs) : m_ref(0) 00035 { 00036 *this = rhs; 00037 } 00038 00039 ~simple_ref_ptr() 00040 { 00041 unref(); 00042 } 00043 00044 simple_ref_ptr &operator=(const simple_ref_ptr &rhs) 00045 { 00046 rhs.m_ref->inc(); 00047 unref(); 00048 m_ref = rhs.m_ref; 00049 00050 return *this; 00051 } 00052 00053 T *operator->() const 00054 { 00055 return get(); 00056 } 00057 00058 T &operator*() const 00059 { 00060 return *get(); 00061 } 00062 00063 T *get() const 00064 { 00065 if (m_ref) return m_ref->get(); 00066 00067 return 0; 00068 } 00069 00070 void reset(T *ptr) 00071 { 00072 unref(); 00073 m_ref = new ref(ptr); 00074 } 00075 00076 typedef T *(simple_ref_ptr<T>::*fake_bool)() const; 00077 00078 operator fake_bool() const 00079 { 00080 return m_ref == 0 ? 0 : &simple_ref_ptr<T>::get; 00081 } 00082 00083 bool operator!() const 00084 { 00085 return m_ref == 0; 00086 } 00087 00088 private: 00089 class ref : public Locker 00090 { 00091 public: 00092 ref(T *ptr) : m_count(1), m_type(ptr) {} 00093 00094 ~ref() 00095 { 00096 delete m_type; 00097 } 00098 00099 unsigned int inc() 00100 { 00101 this->lock(); 00102 ++m_count; 00103 this->unlock(); 00104 return m_count; 00105 } 00106 00107 unsigned int dec() 00108 { 00109 this->lock(); 00110 --m_count; 00111 this->unlock(); 00112 return m_count; 00113 } 00114 00115 T *get() 00116 { 00117 return m_type; 00118 } 00119 00120 T *get() const 00121 { 00122 return m_type; 00123 } 00124 00125 private: 00126 unsigned int m_count; 00127 T *m_type; 00128 }; 00129 00130 void unref() 00131 { 00132 if (m_ref && m_ref->dec() <= 0) 00133 { 00134 delete m_ref; 00135 m_ref = 0; 00136 } 00137 } 00138 00139 private: 00140 ref *m_ref; 00141 }; 00142 00143 template <typename T> 00144 bool operator==(const simple_ref_ptr<T> &lhs, const simple_ref_ptr<T> &rhs) 00145 { 00146 return lhs.get() == rhs.get(); 00147 } 00148 00149 template <typename T> 00150 bool operator!=(const simple_ref_ptr<T> &lhs, const simple_ref_ptr<T> &rhs) 00151 { 00152 return lhs.get() != rhs.get(); 00153 } 00154 00155 #endif // QUICKSP_H_
1.5.5