智能指针:实现简易auto_ptr

auto_ptr简易实现

最近在看《STL源码剖析》,其中迭代器这一章开头提到,iterator可以看做是一种smart_ptr,同时候捷老师给出了部分auto_ptr的实现,我在这里给出完整实现。

namespace smt_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* tmp = pointee;
        pointee = 0;
        return tmp;
    }

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

private:
    T *pointee;
};

}

int main() {
    smt_ptr::auto_ptr<std::string> t(new std::string("smart pointer!"));
    std::cout<<*t<<std::endl;
    smt_ptr::auto_ptr<std::string> tt(t);
    std::cout<<*tt<<std::endl;
    smt_ptr::auto_ptr<std::string> ttt = tt;
    std::cout<<*ttt<<std::endl;
    std::cout<<ttt->size()<<std::endl;
}

运行测试结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值