《C++沉思录》-第六章-句柄:第一部分

来源:互联网 发布:vb循环语句 编辑:程序博客网 时间:2024/04/28 00:47

第五章介绍的代理将会复制所代理的对象,就像复制代理一样。句柄允许保持代理的多态行为的同时,还可以避免进行不必要的复制。

句柄类(handle class)也称为 智能指针(smart pointer)。

一个简单的类:

class Point{public:    Point():m_x(0),m_y(0){}    Point(int x,int y):m_x(x),m_y(y){}    int x()const {return m_x;}    int y()const { return m_y;}    Point& x(int x) { m_x = x; return *this;}    Point& y(int y) { m_y = y; return *this;}private:    int m_x;    int m_y;};

句柄:


class UPoint{    //所有成员都是私有    friend class Handle;    Point p;    int u;//用于计数    UPoint():u(1){}    UPoint(const Point&pv):p(pv),u(1) {}    UPoint(int x,int y):p(x,y),u(1) {}    UPoint(const UPoint &up):p(up.p),u(1) {}};

class Handle{public:    Handle(): up(new UPoint) {}    Handle(int x,int y): up(new UPoint(x,y)) {}    Handle(const Point&p): up(new UPoint(p)) {}    Handle(const Handle &h)    :  up(h.up)    {        //指向相同的UPoint对象,引用计数增加1        ++up->u;    }    Handle& operator=(const Handle &h)    {        ++h.up->u;        if (--up->u == 0)        {//引用计数-1,如果为0,删除UPoint对象            delete up;        }        up = h.up;        return *this;    }    ~Handle()    {        //引用计数为0时,就删除UPoint对象        if (--up->u == 0)        {            delete up;        }    }    int x() const{ return up->p.x(); }    int y() const{ return up->p.y(); }    /*(1)指针语义,互相影响*/    Handle& x(int x0)    {        up->p.x(x0);        return *this;    }    Handle& y(int y0)    {        up->p.y(y0);        return *this;    }    /*(2)值语义,互不影响,写时复制    Handle& x(int xv)    {        allocUp();        up->p.x(xv);        return *this;    }    Handle& y(int yv)    {        allocUp();        up->p.y(yv);        return *this;    }*/private:    UPoint *up;    /*(2)值语义,互不影响*/    void allocUp()    {        //如果为1,说明不是唯一的,那就要复制对象        //使得引用计数为1        if (up->u != 1)        {        --up->u;        up = new UPoint(up->p);        }    }};


原创粉丝点击