C++ 智能指针

#include<iostream>
using namespace std;


class auto_pint{
    class node{
        public:
        int ref_count=0;
        int number=0;
    };
    node * p =nullptr;
    public:
    auto_pint()=default;
    auto_pint(int * pint){
        p = new node();
        p->number = *pint;
        p->ref_count++;
        cout<<p->number<<"引用计数++"<<endl;
    }
    auto_pint(auto_pint & ap)
    {
        if(ap.p){
            p = ap.p;
            p->ref_count++;
        cout<<p->number<<"引用计数++"<<endl;
        }
    }
    ~auto_pint()
    {
        cout<<p->number<<"引用计数--"<<endl;
        if(--p->ref_count == 0){
            cout<<p->number<<"被释放"<<endl;
            delete p;
        }
    }
    int& operator *()
    {
        return p->number;
    }
    auto_pint & operator=(auto_pint & ap)
    {
        //原有的指针对象是否指向了有效数据,如果是,要先减减原来的引用计数
        if(p){
        cout<<p->number<<"引用计数--"<<endl;
            if(--p->ref_count ==0){
            cout<<p->number<<"被释放"<<endl;
                delete p;
            }
        }
        p = ap.p;
        if(p){
            p->ref_count++;
        cout<<p->number<<"引用计数++"<<endl;
        }
    }
};

int main()
{
    auto_pint ap1(new int(100));
    auto_pint ap2(new int (200));
    ap1 = ap2 ;
//  *ap1 = 900;
    auto_pint ap3(ap2);
    cout<<*ap3<<endl;

#if 0
    int * p1 =new int(100);
    int * p2 =new int(200);
    p1 = p2;
    *p1 =900;
    int *p3(p2);
    cout<<*p3<<endl;
#endif
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值