1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
|
#ifndef _INCL_SMART_PTR_H__
#define _INCL_SMART_PTR_H__
template <class T> class make_ptr;
template <class T> class smart_ptr
{
public:
smart_ptr();
smart_ptr(const smart_ptr<T>& p);
smart_ptr(const make_ptr<T>& mkr);
~smart_ptr();
smart_ptr<T>& operator = (const smart_ptr<T>& p);
smart_ptr<T>& operator = (const make_ptr<T>& mkr);
template <class U> operator smart_ptr<U> ();
T& operator * () const;
T* operator -> () const;
private:
smart_ptr(T* ptr_t);
T* p_;
unsigned long int* count_;
template <class> friend class smart_ptr;
template <class> friend class make_ptr;
};
template <class T> class make_ptr
{
public:
make_ptr();
make_ptr(const T& t);
make_ptr(const make_ptr<T>& mkr);
~make_ptr();
private:
smart_ptr<T> ptr_;
template <class> friend class smart_ptr;
};
template <class T> inline smart_ptr<T>::smart_ptr() : p_(NULL), count_(NULL)
{}
template <class T> inline smart_ptr<T>::smart_ptr(const smart_ptr<T>& ptr) : p_(ptr.p_), count_(ptr.count_)
{
++(*count_);
}
template <class T> inline smart_ptr<T>::smart_ptr(const make_ptr<T>& mkr) : p_(mkr.ptr_.p_), count_(mkr.ptr_.count_)
{
++(*count_);
}
template <class T> inline smart_ptr<T>::~smart_ptr()
{
--(*count_);
if((*count_) == 0)
{
delete p_;
delete count_;
}
}
template <class T> inline smart_ptr<T>& smart_ptr<T>::operator = (const smart_ptr<T>& ptr)
{
--(*count_);
if(*count_ == 0)
{
delete p_;
delete count_;
}
p_ = ptr.p_;
count_ = ptr.count_;
++(*count_);
return *this;
}
template <class T> inline smart_ptr<T>& smart_ptr<T>::operator = (const make_ptr<T>& mkr)
{
--(*count_);
if(*count_ == 0)
{
delete p_;
delete count_;
}
p_ = mkr.ptr_.p_;
count_ = mkr.ptr_.count_;
++(*count_);
return *this;
}
template <class T> template <class U> inline smart_ptr<T>::operator smart_ptr<U> ()
{
smart_ptr<U> pU;
pU.p_ = p_;
pU.count_ = count_;
++(*count_);
return pU;
}
template <class T> inline T& smart_ptr<T>::operator * () const
{
return *p_;
}
template <class T> inline T* smart_ptr<T>::operator -> () const
{
return p_;
}
template <class T> inline smart_ptr<T>::smart_ptr(T* ptr_t) : p_(ptr_t)
{
count_ = new unsigned long int(1);
}
// ----------------------------------
template <class T> inline make_ptr<T>::make_ptr() : ptr_(new T)
{}
template <class T> inline make_ptr<T>::make_ptr(const T& t): ptr_(new T(t))
{}
template <class T> inline make_ptr<T>::make_ptr(const make_ptr<T>& mkr) : ptr_(mkr.ptr_)
{}
template <class T> inline make_ptr<T>::~make_ptr()
{}
#endif |
Partager