实现C++智能指针类shared_ptr unique_ptr

template<typename T>
class Msp{
public:
    Msp(T* ptr = nullptr):m_ptr(ptr){
        if(m_ptr == nullptr)
            m_count = new int(0);
        else    
            m_count = new int(1);
    }

    ~Msp(){
        clear();
    }

    Msp(const Msp& msp){
        if(this == &msp)
            return;
        m_ptr = msp.m_ptr;
        m_count = msp.m_count;
        ++*m_count;
    }

    Msp& operator=(const Msp & msp){
        if(this == & msp)
            return *this;
        clear();
        m_ptr = msp->m_ptr;
        m_count = msp->m_count;
        ++*m_count;
        return *this;
    }

    T& operator*(){
        assert(m_ptr == nullptr);
        return *m_ptr;
    }

    T* operator-(){
        assert(m_ptr == nullptr);
        return m_ptr;
    }

    int use_count(){
        return *m_count;
    }

private:
    T* m_ptr;
    int* m_count;

    void clear(){
        if(--*m_count <= 0){
            delete m_ptr;
            delete m_count;
        }
    }
};


// unique_ptr
template<class T>
class MyUnique_ptr{
private:
    T* ptr;
public:
    MyUnique_ptr(T* p): ptr(p){}

    //防拷贝,屏蔽 copy构造和赋值原算法简单粗暴
    MyUnique_ptr(MyUnique_ptr<T>&) = delete;
    MyUnique_ptr<T>& operator=(MyUnique_ptr<T>&) = delete;

    ~MyUnique_ptr(){
        if (ptr){
            delete ptr;
            ptr = nullptr;
        }
    }

    T& operator *(){
        return *ptr;
    }

    T* operator->(){
        return ptr;
    }
};
posted @   子于舟  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示