自己实现的简易版C++智能指针shared_ptr

自己实现的简易版C++智能指针shared_ptr

#include <iostream>
using namespace std;
template<class T>
class Shared_ptr{
    private:
    T* m_ptr;
    int* m_use_count;
    public:
    Shared_ptr(T* ptr=nullptr):m_ptr(ptr){
          cout<<"Constructor"<<endl;
          m_use_count=ptr==nullptr?new int(0):new int(1);
    }
    Shared_ptr(const Shared_ptr& other):m_ptr(other.m_ptr),m_use_count(other.m_use_count){
        cout<<"Copy Constructor"<<endl;
        ++(*other.m_use_count);
    }
    Shared_ptr& operator=(const Shared_ptr& other) {
        cout<<"Copy assignment"<<endl;
         if (--(*m_use_count) == 0)
        {
            delete m_ptr;
            delete m_use_count;
            m_ptr=nullptr;
            m_use_count=nullptr;
        }
        m_ptr=other.m_ptr;
        m_use_count=other.m_use_count;
        ++(*other.m_use_count);
        return *this;
    }
    Shared_ptr(Shared_ptr&& other){
        cout<<"Move Constructor"<<endl;
        m_ptr=other.m_ptr;
        m_use_count=other.m_use_count;
        other.m_use_count=nullptr;
        other.m_ptr=nullptr;
    }
    Shared_ptr& operator=(Shared_ptr&& other) {
                if (--*m_use_count == 0)
        {
            delete m_ptr;
            delete m_use_count;
            m_ptr=nullptr;
            m_use_count=nullptr;
        }
        cout<<"Move assignment"<<endl;
        m_ptr=other.m_ptr;
        m_use_count=other.m_use_count;
        other.m_ptr=nullptr;
        other.m_use_count=nullptr;
        return *this;
    }
    ~Shared_ptr(){
        cout<<"Destructor"<<endl;
        if(m_ptr&&m_use_count&&--(*m_use_count)==0){
            delete m_ptr;
            delete m_use_count;
            m_ptr=nullptr;
            m_use_count=nullptr;
        }
    }
    int get_use_count(){
        return *m_use_count;
    }
};
int main(int argc,char** argv)
{
    Shared_ptr<int> p(new int(10));
    auto q=p;
    cout<<q.get_use_count()<<" "<<p.get_use_count()<<endl;
    auto t(move(q));
    cout<<t.get_use_count()<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值