00001 #ifndef HANDLE_H
00002 #define HANDLE_H
00003
00014
00015 #include <iostream>
00016
00017 template <typename T>
00018 class Handle {
00019
00020 public:
00024 Handle();
00025
00029 Handle(T* ptr);
00030
00034 Handle(const Handle& rhs);
00035
00039 ~Handle();
00040
00044 Handle& operator=(const Handle& rhs);
00045
00049 T* operator->() const;
00050
00054 T& operator*() const;
00055
00059 void release();
00060
00064 bool operator==(const Handle& rhs);
00065
00069 bool operator!=(const Handle& rhs);
00070
00071 private:
00072 T* p;
00073
00074 void init();
00075 };
00076
00077
00078 template <typename T>
00079 Handle<T>::Handle() : p(0)
00080 {}
00081
00085 template <typename T>
00086 Handle<T>::Handle(T* realPtr) : p(realPtr)
00087 {
00088 init();
00089 }
00090
00094 template <typename T>
00095 Handle<T>::Handle(const Handle& rhs) : p(rhs.p)
00096 {
00097 init();
00098 }
00099
00100
00104 template <typename T>
00105 Handle<T>& Handle<T>::operator=(const Handle& rhs)
00106 {
00107 if (p != rhs.p) {
00108 if (p) {
00109 p->release();
00110 }
00111
00112 p = rhs.p;
00113 init();
00114 }
00115 return *this;
00116 }
00117
00118
00122 template <typename T>
00123 void Handle<T>::init()
00124 {
00125 if (p == 0) {
00126 return;
00127 }
00128
00129 p->add_ref();
00130 }
00131
00135 template <typename T>
00136 Handle<T>::~Handle()
00137 {
00138 if (p) p->release();
00139 }
00140
00141
00145 template <typename T>
00146 T* Handle<T>::operator->() const
00147 {
00148 return p;
00149 }
00150
00151
00155 template <typename T>
00156 T& Handle<T>::operator*() const
00157 {
00158 return *p;
00159 }
00160
00164 template <typename T>
00165 void Handle<T>::release()
00166 {
00167 if (p) p->release();
00168 p = 0;
00169 }
00170
00171
00175 template <typename T>
00176 bool Handle<T>::operator==(const Handle& rhs)
00177 {
00178 if (p == rhs.p)
00179 return true;
00180
00181 return false;
00182 }
00183
00187 template <typename T>
00188 bool Handle<T>::operator!=(const Handle& rhs)
00189 {
00190 if (p != rhs.p)
00191 return true;
00192
00193 return false;
00194 }
00195
00199 template <typename T>
00200 std::ostream& operator<<(std::ostream& o, const Handle<T>& handle)
00201 {
00202 o << *handle;
00203 return o;
00204 }
00205
00206 #endif // HANDLE_H