auto_ptr

template<class T>
class auto_ptr
{
public:
    explicit auto_ptr(T *p = 0): pointee(p) {}
    template<class U>
    auto_ptr(auto_ptr<U> &rhs): pointee(rhs.release()) {}

    ~auto_ptr() { delete pointee; }
    // 拷贝构造函数和拷贝赋值运算符都没有传常量参数进入,因为这里有所有权的转移
    template<class U>
    auto_ptr<T>& operator=(auto_ptr<U> &rhs)
    {
        if (this != &rhs) reset(rhs.release());
        return *this;
    }

    T& operator*() const { return *pointee; }
    T* operator->() const { return pointee; }

    T* get() const { return pointee; }
    T* release()
    {
        T *oldPointee = pointee;
        pointee = 0;
        return oldPointee;
    }

    void reset(T *p = 0)
    {
        if (pointee != p)
        {
            delete pointee;
            pointee = p;
        }
    }

private:
    T *pointee;

template<class U> friend class auto_ptr<U>;
};

猜你喜欢

转载自blog.csdn.net/ndzjx/article/details/88225316