zoukankan      html  css  js  c++  java
  • 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
    }
    
  • 相关阅读:
    实验 7 综合练习一
    实验或作业模版: 实验 6-1 最大公约数 最小公倍数
    实验 6 数组1
    Pro
    作业 4 函数应用
    老大
    双端队列
    zxa and leaf
    Baby Ming and Matrix games
    The more, The Better
  • 原文地址:https://www.cnblogs.com/Sico2Sico/p/5384240.html
Copyright © 2011-2022 走看看