美文网首页
智能指针

智能指针

作者: 徐振杰 | 来源:发表于2019-07-11 18:04 被阅读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;
    }
    

    相关文章

      网友评论

          本文标题:智能指针

          本文链接:https://www.haomeiwen.com/subject/wlxjkctx.html