智能指针的简单分析(二)

自己实现一个shared_ptr.

template<typename Ty>
class MySharedPtr
{
    typedef typename Ty* pointer;
    typedef typename Ty* MyRef;
private:
    int* m_pnCount;
    pointer m_ptPointer;

public:
    MySharedPtr() : m_pnCount(new int()), m_ptPointer(nullptr) {};
    MySharedPtr(pointer p) : m_pnCount(new int(1)), m_ptPointer(p) {};

    MySharedPtr(const MySharedPtr<Ty>& other)
    {
        if (!other) { return; }
        if (&other == this) { return; }
        this->m_pnCount = other.m_pnCount;
        this->m_ptPointer = other.m_ptPointer;
        (*m_pnCount)++;
    }

    MySharedPtr(MySharedPtr<Ty>&& other)
    {
        if (!other) { return; }
        if (&other == this) { return; }
        this->m_pnCount = other.m_pnCount;
        this->m_ptPointer = other.m_ptPointer;
        (*m_pnCount)++;
        other.reset();
    }

    MySharedPtr& operator= (const MySharedPtr<Ty>& other)
    {
        if (!other) { return *this; }
        if (&other == this) { return *this; }
        this->m_pnCount = other.m_pnCount;
        this->m_ptPointer = other.m_ptPointer;
        (*m_pnCount)++;
        { return *this; }
    }

    MySharedPtr& operator= (MySharedPtr<Ty>&& other)
    {
        if (!other) { return *this; }
        if (&other == this) { return *this; }
        this->m_pnCount = other.m_pnCount;
        this->m_ptPointer = other.m_ptPointer;
        (*m_pnCount)++;
        other.reset();
        { return *this; }
    }

    ~MySharedPtr() { free(); };

    pointer get() const {return m_ptPointer;}
    void swap(MySharedPtr<Ty>& other)
    {
        auto pnCount_Temp = other.m_pnCount;
        auto ptPointer_Temp = other.m_ptPointer;
        other.m_pnCount = this->m_pnCount;
        other.m_ptPointer = this->m_ptPointer;
        this->m_pnCount = pnCount_Temp;
        this->m_ptPointer = ptPointer_Temp;
    }
    void reset(){ free(); }
    long use_count() const _NOEXCEPT { return *m_pnCount; };
    bool unique() const { return (use_count() == 1); }

    operator bool() const { return (m_ptPointer != nullptr); };
    pointer operator ->() const {return m_ptPointer;}
    MyRef operator *() const { return m_ptPointer; }
private:
    void free()
    {
        if (m_pnCount != nullptr)
        {
            (*m_pnCount)--;
            if (*m_pnCount == 0)
            {
                delete m_pnCount;

                if (nullptr != m_ptPointer)
                {
                    delete m_ptPointer;
                }
            }
        }

        m_pnCount = nullptr;
        m_ptPointer = nullptr;
    }
};


 

猜你喜欢

转载自blog.csdn.net/chicaidecaiji/article/details/81067198
今日推荐