美文网首页C++程序员
C++ 98里面auto_ptr的源码

C++ 98里面auto_ptr的源码

作者: DayDayUpppppp | 来源:发表于2017-05-04 19:56 被阅读0次

代码来源:SGI STL

template <class _Tp> class auto_ptr {
private:
    _Tp* _M_ptr; //实际wrap的指针

public:
    typedef _Tp element_type;

    // 显示构造函数,防止auto_ptr<A> pAObj1 = new A();隐士构造
    explicit auto_ptr(_Tp* __p = 0) __STL_NOTHROW : _M_ptr(__p) {}

    // 复制构造函数,知道为什么参数是&吗?
    auto_ptr(auto_ptr& __a) __STL_NOTHROW : _M_ptr(__a.release()) {}
    template <class _Tp1> auto_ptr(auto_ptr<_Tp1>& __a) __STL_NOTHROW
        : _M_ptr(__a.release()) {}

    // 赋值构造函数
    auto_ptr& operator=(auto_ptr& __a) __STL_NOTHROW {
        if (&__a != this) {
            delete _M_ptr;
            _M_ptr = __a.release();
        }
        return *this;
    }

    template <class _Tp1>
    auto_ptr& operator=(auto_ptr<_Tp1>& __a) __STL_NOTHROW {
        if (__a.get() != this->get()) {
            delete _M_ptr;
            _M_ptr = __a.release();
        }
        return *this;
    }

    ~auto_ptr() { delete _M_ptr; }

    // 智能指针一般都要重载"*"和"->"操作符
    _Tp& operator*() const __STL_NOTHROW {
        return *_M_ptr;
    }
    _Tp* operator->() const __STL_NOTHROW {
        return _M_ptr;
    }
    _Tp* get() const __STL_NOTHROW {
        return _M_ptr;
    }
    _Tp* release() __STL_NOTHROW {
        _Tp* __tmp = _M_ptr;
        _M_ptr = 0;
        return __tmp;
    }
    void reset(_Tp* __p = 0) __STL_NOTHROW {
        if (__p != _M_ptr) {
            delete _M_ptr;
            _M_ptr = __p;
        }
    }
};

阅读代码就会发现,auto_ptr不能共享内存,在同一时间,只有一个auto_ptr指向一个指定的内存。

相关文章

网友评论

    本文标题:C++ 98里面auto_ptr的源码

    本文链接:https://www.haomeiwen.com/subject/wzudtxtx.html