More Effective中auto_ptr实现

template
class auto_ptr
{
    public :
        //使用explicit关键字避免隐式转换
        explicit auto_ptr(T* p=0);

        ~auto_ptr();

        //使用另一个类型兼容的auto_ptr来初始化一个新的auto_ptr
        template
        auto_ptr(auto_ptr& rhs);

        template
        auto_ptr& operator=(auto_ptr& rhs);

        T& operator*() const;
        T* operator->() const;

        //返回原始对象的指针
        T* get() const;
        //放弃指针的所以权
        T* release();
        //删除原有指针并获得指针的p的所有权
        void reset(T* p=0);

    private:
        T* pointee;
template
friend class auto_ptr

};

template
auto_ptr::auto_ptr(T* p)
    :pointee(p)
{}

template
    template
auto_ptr::auto_ptr(auto_ptr& rhs)
    :pointee(rhs.release())
{}

template
auto_ptr::~auto_ptr()
{
    delete pointee;
}

template
    template
auto_ptr& auto_ptr::operator=(auto_ptr& rhs)
{
    if(this!=&rhs)
        reset(rhs.release());
    return *this;
}

template
T& auto_ptr::operator*() const
{
    return *pointee;
}

template
T* auto_ptr::operator->() const
{
    return pointee;
}

template
T* auto_ptr::get() const
{
    return pointee;
}

template
T* auto_ptr::release()
{
    T* oldpointee=pointee;
    pointee=0;
    return oldpointee;
}

template
void auto_ptr::reset(T* p)
{
    if(pointee!=p)
    {
        delete pointee;
        pointee=p;
    }
}

你可能感兴趣的:(面试题集合)