智能指针

2019-07-11  本文已影响0人  徐振杰
#include<iostream>
#include<string>

using namespace std;

class Point{
public:
    Point(int xVal = 0,int yVal = 0) : x(xVal), y(yVal) {}
    int getX() const {return x;}
    int getY() const {return x;}
    void setX(int xVal)  {x = xVal;}
    void setY(int yVal)  {y = yVal;}
private:
    int x,y;
};

class U_ptr{
private:
    friend class Smart_ptr;

    U_ptr(Point* dummy):p(dummy),count(1){}
    ~U_ptr(){
        delete p;
    }  
    
    int count;
    Point* p;
    
};

class Smart_ptr{
public:
    Smart_ptr(Point* ptr):rp(new U_ptr(ptr)){}
    
    Smart_ptr(Smart_ptr* ptr):rp(ptr.rp){
        rp->count ++ ;
    }
    
    Smart_ptr& operator=(Smart_ptr* rhs){
        rhs.rp->count++;
        if(--rp->count==0){
            delete rp;
        }
        rp = rhs.rp;
        return *this;
    }
    
    ~Smart_ptr(){
        if(--rp->count==0)
            delete rp;
        else
            cout<<"还有 "<<rp->count<<endl;
    }
private:
    U_ptr* rp;
};

int main(){
    Point* p = new Point(4,3);
    {
        Smart_ptr sptr1(p);
        {
            Smart_ptr sptr2(sptr1);
            {
                Smart_ptr sptr2 = sptr1;
            }
        }
    }
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读