自定义智能指针模板类

1、简单的

template<class T>
class Auto_ptr1
{
    T* m_ptr;
public:
    // Pass in a pointer to "own" via the constructor
    Auto_ptr1(T* ptr=nullptr)
        :m_ptr(ptr)
    {
    }
    
    // The destructor will make sure it gets deallocated
    ~Auto_ptr1()
    {
        delete m_ptr;//核心就是在生命周期结束自动释放
    }
 
    // Overload dereference and operator-> so we can use Auto_ptr1 like m_ptr.
    T& operator*() const { return *m_ptr; }
    T* operator->() const { return m_ptr; }
};
 

2、独占式,拷贝时把原来的回收

template<class T>
class Auto_ptr2
{
    T* m_ptr;
public:
    Auto_ptr2(T* ptr=nullptr)
        :m_ptr(ptr)
    {
    }
    
    ~Auto_ptr2()
    {
        delete m_ptr;
    }
 
    // A copy constructor that implements move semantics
    Auto_ptr2(Auto_ptr2& a) // note: not const
    {
        m_ptr = a.m_ptr; // transfer our dumb pointer from the source to our local object
        a.m_ptr = nullptr; // make sure the source no longer owns the pointer
    }
    
    // An assignment operator that implements move semantics
    Auto_ptr2& operator=(Auto_ptr2& a) // note: not const
    {
        if (&a == this)
            return *this;
 
        delete m_ptr; // make sure we deallocate any pointer the destination is already holding first
        m_ptr = a.m_ptr; // then transfer our dumb pointer from the source to the local object
        a.m_ptr = nullptr; // make sure the source no longer owns the pointer
        return *this;
    }
 
    T& operator*() const { return *m_ptr; }
    T* operator->() const { return m_ptr; }
    bool isNull() const { return m_ptr == nullptr;  }
};
 

 

posted @ 2019-07-04 00:23  朱小勇  阅读(469)  评论(0编辑  收藏  举报