C++11 自制智能指针

实现的一个和系统的shared_ptr保持大概一致的智能指针,能够大概一窥智能指针的原理

/**
 * 自己实现一个简单的智能指针类来理解原理
 * */
#include<iostream>
#include<memory>
using namespace std;
template<typename T>
class mptr{
    T* ptr;
    int *count;     //引用计数,用来判断对象是否应该析构
public:
    mptr(T* p){     //初始化
        ptr=p;
        count=new int(1);
    }
    mptr(const mptr& obj){//拷贝构造,引用计数+1
        ptr=obj.ptr;
        count=obj.count;
        (*count)++;
    }
    mptr<T>& operator=(const mptr<T>& obj){
        //赋值或者复制的时候,引用计数+1,析构的时候判断是否为0,0就释放空间
        ptr=obj.p;
        count=obj.count;
        (*count)++;
        return *this;
    }
    ~mptr(){
        (*count)--;
        if((*count)==0){
            delete ptr;       //引用计数为0的时候,释放内存
            delete count;
        }
    }
    int use_count(){
        return (*count);
    }

};
class a{
public:
    a(){
        cout<<"construct"<<endl;
    }
    ~a(){
        cout<<"del"<<endl;
    }
};
int main(){
    //shared_ptr<a> ptra=make_shared<a>();      //系统自带的shared_ptr
    mptr<a> ptra(new a);                        
    cout<<"ptra end"<<ptra.use_count()<<endl;
    //shared_ptr<a> ptrb=ptra;                  //系统自带的shared_ptr
    mptr<a> ptrb=ptra;                          //自己的这个模拟类能够保持和系统的shared_ptr有一样的效果
    cout<<"end "<<ptra.use_count()<<" "<<ptrb.use_count()<<endl;
    
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值