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
}
posted @ 2016-03-30 13:53  夜色下的港湾  Views(176)  Comments(0Edit  收藏  举报