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
    }
    
  • 相关阅读:
    概要设计说明书
    第二次冲刺——第6天
    第二次冲刺——第5天
    第二次冲刺——第4天
    开发文档
    “来用”Beta版使用说明
    项目总结
    团队站立会议10(第二阶段)
    团队站立会议9(第二阶段)
    团队站立会议8(第二阶段)
  • 原文地址:https://www.cnblogs.com/Sico2Sico/p/5384240.html
Copyright © 2011-2022 走看看