把C++ Primer第四版中智能指针的示例代码改为了类模板,并增加了几个函数。
template <typename T> class U_Ptr
{
template <typename T> friend class lxlshared_ptr;
T *tp;
size_t use;
U_Ptr(T *p) : tp(p), use(1) {}
~U_Ptr() {delete tp;}
};
template <typename T> class lxlshared_ptr
{
public:
lxlshared_ptr(T *p) : ptr(new U_Ptr<T>(p)) {}
lxlshared_ptr(const lxlshared_ptr &orig) : ptr(orig.ptr) {++ptr->use;}
lxlshared_ptr& operator= (const lxlshared_ptr&);
~lxlshared_ptr()
{
if (--ptr->use == 0)
delete ptr;
}
long use_count() const {return ptr->use;}
T& operator* () {return *ptr->tp;}
T* operator-> () {return ptr->tp;}
friend bool operator== (const lxlshared_ptr &lhs, const lxlshared_ptr &rhs) {return lhs.ptr == rhs.ptr;}
friend bool operator!= (const lxlshared_ptr &lhs, const lxlshared_ptr &rhs) {return !(lhs == rhs);}
private:
U_Ptr<T> *ptr;
};
template <typename T> lxlshared_ptr<T>& lxlshared_ptr<T>::operator= (const lxlshared_ptr<T> &rhs)
{
++rhs.ptr->use;
if (--ptr->use == 0)
delete ptr;
ptr = rhs.ptr;
return *this;
}