智能指针简单实现-shared_ptr

SharedPtr定义

//shared_ptr
template<typename T>
class SharedPtr{
public:    
    SharedPtr(T* p = NULL):m_ptr(p){
        if (NULL != p){
            pm_count = new int(1);
            cout<<"create: m_ptr(*p = null). count = 1."<<endl;
        } else {
            pm_count = new int(0);
            cout<<"create: m_ptr(*p != null). count = 0."<<endl; 
        }
    }

    SharedPtr(SharedPtr<T>& p){
        if (this != &p){
            this->m_ptr = p.m_ptr;
            this->pm_count = p.pm_count;
            ++(*this->pm_count);
            cout<<"create: m_ptr(&p). count = "<<*pm_count<<endl;
        }
    }
    SharedPtr& operator=(SharedPtr<T>& p){
        if (this != &p){
            cout<<"operator =: this != p old count = "<<*pm_count<<endl;
            --(*pm_count);
            if (0 == *pm_count){
                delete m_ptr;
                delete pm_count;
            }
            m_ptr = p.m_ptr;
            pm_count = p.pm_count;
            ++(*pm_count);
            cout<<"operator =: this != p new count = "<<*pm_count<<endl;
        }else{
            cout<<"operator =: this == p "<<endl;
        }
        
        return *this;
    }
    
    ~SharedPtr(){
        if (NULL != m_ptr ){
            cout<<"delete: m_ptr is not null. count = "<<*pm_count<<endl;
            --(*pm_count);
            if (0 == *pm_count){
                cout<<"delete: count is 0 "<<endl;
                delete m_ptr;
                delete pm_count;
            }else{
                cout<<"delete: count!= 0; count = "<<*pm_count<<endl;
            }
        }else{
            cout<<"delete: m_ptr is null."<<endl;
        }
    }
    
    T& operator*(){
        return *m_ptr;
    }
    
    T* operator->(){
        return m_ptr;
    }
    
protected:
    T* m_ptr;
    int *pm_count;
};

测试代码

int main()
{
    cout<<"Test start."<<endl;
    SharedPtr<int> p1(new int(100));
    SharedPtr<int> p2(p1);
    SharedPtr<int> p3(p2);
    
    p1 = p2;
    p1 = p3;
    p3 = p3;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值