《C++沉思录》-第七章-句柄:第二部分

第六章谈及一种向类中添加句柄和引用计数的技术,以能够通过值控制引用计数就能够高效地“复制”该类的对象。这种技术有一个明显的缺点:为了把句柄绑定到类T的对象上,必须定义一个具有类型T的成员的新类。


分离引用计数:

class Handle
{
public:
    Handle(): u(new int(1)), p(new Point) {}
    Handle(int x, int y): u(new int(1)), p(new Point(x, y)) {}
    Handle(const Point& p0): u(new int(1)), p(new Point(p0)) {}
    Handle(const Handle& h): u(h.u), p(h.p)  {++*u;}
    Handle& operator=(const Handle& h)
    {
        ++*h.u;
        if (--*u == 0)
        {
            delete u;
            u = NULL;
            delete p;
            p = NULL;
        }
        u = h.u;
        p = h.p;
        return *this;
    }
    ~Handle()
    {
        if (--*u == 0)
        {
            delete u;
            u = NULL;
            delete p;
            p = NULL;
        }
    }
private:
    Point* p;
    int* u; //指向引用计数的指针
};

对引用计数的抽象:

class UseCount
{
public:
    UseCount():count(new int(1)){}
    UseCount(const UseCount& uc):count(uc.count){ ++*count;}
    UseCount& operator=(const UseCount &u)
    {
       reattach(u);
       return *this;
    }
    ~UseCount()
    {
       if (--*count == 0)
       {
           delete count;
           count == NULL;
       }
    }
    bool only() { return *count == 1;} //判断是否只指向一个计数,用于判断是否要删除
    bool reattach(const UseCount &u)  //重新连接,用于复制
    {
      ++*u.count;
      if (--*u.count == 0)
      {
          delete count;
          count = u.count;
          return true;
      }
      count = u.count;
      return false;
    }
    bool makeonly()                  //分配一个新的,用于写时复制技术
    {
      if (*count == 1)
          return false;
      --*count;
      count = new int(1);
      return true;
    }
private:
    int *count;//计数
};
class Handle
{
public:
    //由于构造函数可以缺省UsrCount构造函数的行为,所以变得简单了
    Handle(): p(new Point) {}
    Handle(int x, int y): p(new Point(x, y)) {}
    Handle(const Point& p0): p(new Point(p0)) {}
    Handle(const Handle& h): u(h.u), p(h.p) {}
    Handle& operator=(const Handle& h)
    {
        if (u.reattach(h.u))
        {
            delete p;
        }
        p = h.p;
        return *this;
    }
    ~Handle()
    {
        if (u->only())
        {
            delete p;
            p = NULL;
        }
    }
    int x() const {return p->x();}
    Handle& x(int x0)
    {
        if (y.makeonly())
        {
            p = new Point(*p);
        }
        p->x(x0);
        return *this;
    }
private:
    Point* p;
    UseCount* u; //指向引用计数的指针
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值