C++ shared_ptr的實現

自己寫了一個shared_ptr的實現。如有錯漏,還望指摘。

template<class T>
class MySharedPtr
{
private:
    T* ptr = nullptr;
    std::atomic_uint* num = nullptr;

public:
    constexpr MySharedPtr() noexcept {}
    constexpr MySharedPtr(std::nullptr_t) noexcept {}
    MySharedPtr(T* p) : ptr(p) {
        num = new std::atomic_uint(1);
    };
    MySharedPtr(const MySharedPtr& p) noexcept : ptr(p.ptr), num(p.num) {
        ++(*num);
    };
    MySharedPtr(MySharedPtr&& p) noexcept {
        std::swap(ptr, p.ptr);
        std::swap(num, p.num);
    }
    MySharedPtr& operator = (const MySharedPtr& _right) noexcept {
        ptr = _right.ptr;
        num = _right.num;
        ++(*num);
        return *this;
    }
    MySharedPtr& operator = (MySharedPtr&& _right) noexcept {
        std::swap(ptr, _right.ptr);
        std::swap(num, _right.num);
        return *this;
    }
    ~MySharedPtr() noexcept {
        if (num != nullptr)
        {
            --(*num);
            if (!(*num)) {
                delete ptr;
                ptr = nullptr;

                delete num;
                num = nullptr;
            }
        }
    }
    T* operator ->() const noexcept
    {
        return ptr;
    }
    T& operator *() const noexcept
    {
        return *ptr;
    }
    T& operator [] (long long index) const noexcept
    {
        return ptr[index];
    }

    T* get()
    {
        return ptr;
    }
    unsigned int use_count()
    {
        return *num;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章