《C++沉思录》将计数器和对象分离开

class point
{
public:
 point(int x = 0, int y = 0) : xval(x), yval(y) { }
 int x(void) const { return xval; }
 int y(void) const { return yval; }
 point &x(int xv) { xval = xv; return *this; }
 point &y(int yv) { yval = yv; return *this; }
private:
 int xval, yval;
};

class useCount
{
public:
 useCount(void) : p(new int(1)) { }
 useCount(const useCount& u) : p(u.p) { ++*p; }
 useCount& operator=(const useCount&);
 
 bool Only(void) { return *p == 1; }
 bool reattach(const useCount &u)
 {
  ++*u.p;
  if (--*p == 0)
  {
   delete p;
   p = u.p;
   return true;
  }
  p = u.p;
  return false;
 }
 bool makeOnly(void)
 {
  if (*p == 1)
  {
   return false;
  }
  --*p;
  p = new int(1);
  return true;
 }

 ~useCount(void)
 {
  if (--*p == 0)
  {
   delete p;
  }
 }
private:
 int *p;
};


class Handle
{
public:
 Handle(void) : up(new point) { }
 Handle(int x,int y) : up(new point(x, y)) { }
 Handle(const point& p) : up(new point(p)) {}
 Handle(const Handle& h) :up(h.up), u(h.u){}
 Handle& operator=(const Handle &h)
 {
  if (u.reattach(h.u))
  {
   delete up;
  }
  up = h.up;
  return *this;
 }

 int x(void) const
 {
  return up->x();
 }
 Handle& x(int x0)
 {
  if (u.makeOnly())
  {
   up = new point(*up);
  }
  
  up->x(x0);
  return *this;
 }
 ~Handle(void)
 {
  if (u.Only())
  {
   delete up;
  }
 }

private:
 point *up;
 useCount u;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值