00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024 #ifndef SMARTPTR_H
00025 #define SMARTPTR_H
00026
00027 #include <iostream>
00028
00029 class Ptr {
00030 public:
00031
00032 Ptr() {
00033 ptr=NULL;
00034 refcount=1;
00035 }
00036
00037 Ptr(void* sth) {
00038 ptr=sth;
00039 refcount=1;
00040 }
00041
00042 ~Ptr() {
00043
00044 }
00045 int refcount;
00046 void * ptr;
00047 };
00048
00049 template <class T>
00050 class SmartPtr
00051 {
00052
00053
00054
00055
00056
00057
00058 public:
00059 SmartPtr();
00060 SmartPtr(T* something);
00061 SmartPtr(Ptr *voidptr) {
00062 if(voidptr)
00063 {
00064 this->ptr=voidptr;
00065 this->ptr->refcount++;
00066 }
00067 else
00068 this->ptr=new Ptr();
00069 }
00070 SmartPtr(const SmartPtr & ref);
00071 SmartPtr(int onlyNull);
00072 SmartPtr& operator=(const SmartPtr& old);
00073
00074 operator Ptr*() {if (this->ptr->ptr)
00075 return this->ptr;
00076 else
00077 return (Ptr*)NULL;
00078 }
00079
00080
00081
00082
00083 ~SmartPtr();
00084 T& operator*() const;
00085 T* operator->() const;
00086
00087 private:
00088 Ptr * ptr;
00089 };
00090
00091 template <class T>
00092
00093 SmartPtr<T>::SmartPtr() {
00094 ptr = new Ptr();
00095 }
00096
00097 template <class T>
00098 SmartPtr<T>::SmartPtr(T* something) {
00099 ptr = new Ptr(something);
00100 }
00101
00102 template <class T>
00103 SmartPtr<T>::SmartPtr(const SmartPtr& old) {
00104 old.ptr->refcount++;
00105 this->ptr = old.ptr;
00106 this->ptr->refcount=old.ptr->refcount;
00107 }
00108
00109 template <class T>
00110 SmartPtr<T>::~SmartPtr() {
00111 if (!(--(ptr->refcount))) {
00112 delete (T*)(ptr->ptr);
00113 delete ptr;
00114 }
00115 }
00116
00117 template <class T>
00118 T& SmartPtr<T>::operator*() const {
00119 return *((T*)(ptr->ptr));
00120 }
00121
00122 template <class T>
00123 T* SmartPtr<T>::operator->() const {
00124 if (!ptr) {
00125 return 0;
00126 }
00127 return (T*)(ptr->ptr);
00128 }
00129
00130
00131
00132 template <class T>
00133 SmartPtr<T>::SmartPtr(int )
00134 {
00135 ptr=new Ptr();
00136 }
00137
00138 template <class T>
00139 SmartPtr<T>& SmartPtr<T>::operator=(const SmartPtr& old) {
00140 if (this==&old)
00141 return *this;
00142 if (this->ptr)
00143 if(!(--this->ptr->refcount))
00144 {
00145 delete (T*)(this->ptr->ptr);
00146 delete this->ptr;
00147 this->ptr=NULL;
00148 }
00149 this->ptr=old.ptr;
00150 old.ptr->refcount++;
00151
00152 return *this;
00153 }
00154 #endif
00155