简易实现shared_ptr智能指针

shared_ptr智能指针与auto_ptr智能指针不同的是,拷贝构造或赋值后,原来的指针仍然能够使用。
原因是这种指针用一个引用计数来计算有多少个指针指向同一个空间,拷贝构造和赋值,都会让计数+1,智能指针析构的时候计数-1,计数为0才释放内存。所以根据这几点可以自己实现shared_ptr智能指针的功能。

#include <iostream>
using namespace std;
template<typename T>
class mshared_ptr{
    T* ptr;
   /* int count;//不能用普通变量来保存计数,因为const对象无法修改
   成员变量*/
    int *count;//办法是用指针

    public:
    //构造
    mshared_ptr(T *_ptr=NULL):ptr(_ptr)
    {
        count=new int(0);
        if(ptr!=NULL)
            *count=1;
    }
    //拷贝构造
    mshared_ptr(const mshared_ptr &r)
    {
        cout<<"拷贝构造"<<endl;
        ptr=r.ptr;//让两个指针指向同一个地方
        count=r.count;//让count指针和原来的指向同一个地方
        ++*r.count;//原来的对象的引用计数++
    }
    //赋值运算符重载
    mshared_ptr &operator=(const mshared_ptr &r)
    {
        if(--*count==0)
        {
            delete ptr;
            delete count;
            cout<<"赋值重载中释放内存"<<endl;
        }
        ptr=r.ptr;
        count=r.count;
        ++*r.count;
        return *this;
    }
    //解引用
    T operator*()
    {
        return *ptr;
    }
    //析构
    ~mshared_ptr()
    {
        if(--*count==0)
        {
            delete ptr;
            delete count;
            cout<<"析构中释放内存"<<endl;
        }
    }
    //引用计数
    int use_count()
    {
        return *count;
    }
};

int main(void)
{
    mshared_ptr<double> ptr(new double(3.14));
    cout<<*ptr<<endl;
    // {
        mshared_ptr<double> ptr1=ptr;
        cout<<*ptr<<endl;
        cout<<*ptr1<<endl;
        cout<<"引用计数是"<<ptr.use_count()<<
            "\t"<<ptr1.use_count()<<endl;
    // }
    // cout<<"ptr1删除后ptr引用计数是"<<ptr.use_count()<<endl;

    mshared_ptr<double> ptr_n1(new double(1.59));
    ptr_n1=ptr;/*在让ptr_n1指向新的空间之前,ptr_n1原来的空间的
    引用计数要-1,如果为0要清除*/
    cout<<"赋值给ptr_n1后引用计数是"<<ptr.use_count()<<endl;

}


这里写图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值