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;
};