auto_ptr 实现

#ifndef MYAUTOPTR_H
#define MYAUTOPTR_H

template<typename _T>
class MyAutoPtr
{
private:
    _T* _ptr;
        
public:
    typedef _T element_type;
    
    explicit
    MyAutoPtr(element_type * ptr = 0)
    {
        _ptr = ptr;
    }
    
    ~MyAutoPtr()
    {
        // delete 空指针也无妨
        delete _ptr;
    }
    
    MyAutoPtr(MyAutoPtr<_T>& a)
    {
        _ptr = a.release();
    }
    
    MyAutoPtr& operator=(MyAutoPtr<_T>& a)
    {
        reset(a.release());
        return *this;
    }
    
    void reset(element_type* ptr = 0)
    {
        // 直接释放原来的,设置现在的
        if (ptr != _ptr)
        {
            delete _ptr;
            _ptr = ptr;
        }
    }
    
    element_type * release()
    {
        // release 只是转移指针
        element_type * tmp = _ptr;
        _ptr = 0;
        return tmp;
    }
    
    element_type* operator->()
    {
        return _ptr;
    }
    
    element_type& operator*()
    {
        return *_ptr;
    }
};

#endif    /* MYAUTOPTR_H */

可能 auto_ptr 最令人诟病的就是指针所有权转移的缺陷,不过简单的场合使用起来还是非常方便。

原文地址:https://www.cnblogs.com/wendellyi/p/4954801.html