//句柄解决方案二
//问题:
//成对的删除和创造 计数器对象 和 Point对象
//为了理清关系,所以将抽象化计数器类。
//计数器一旦抽象化了
//提供很多好处:
//这个好处之一比如:
//假设操作
//Handle h1( 3, 4 );
//Handle h2 = h;
//h2.x(5); //修改Point
//int n = h.x //3还是5?
//可以增加一个接口操作,提供即可以复制,也可以不复制。
//可以在计数器类中添加这个接口
//第二个方案
class Point{
int xval;
int yval;
public:
Point( ):xval(0),yval(0){}
Point( int x, int y ): xval(x), yval(y){}
int x() const{
return xval;
}
int y() const{
return yval;
}
Point& x( int _x ){
xval = _x;
return *this;
}
Point& y( int _y ){
yval = _y;
return *this;
}
};
class UseCount{
public:
UseCount(): p(new int(1)){}
UseCount( const UseCount& u ):p(u.p){
++*u.p;
}
~UseCount(){
if( --*p == 0 )
delete p;
}
//可以提供方便化的很多操作
//是否只有一个Handle存储着唯一Point对象
bool only(){
if( *p == 1 )
return true;
return false;
}
//控制着复制,但又有点超过了复制的作用
bool reattach( const UseCount& u ){
++*u.p;
if( --*p == 0 ){
//是否是唯一个
delete p;
p = u.p;
return true;
}
p = u.p;
return false;
}
//解决上面说到的好处之一
bool makeonly(){
if( *p == 1 )
return false;
--*p;
p = new int(1);
return true;
}
private:
//复制操作符将被reattach代替
UseCount& operator=( const UseCount& u );
int* p;
};
class Handle{
public:
Handle( ):p(new Point(0, 0)){}
Handle( const Handle& _h ):p(_h.p), u(_h.u){}
Handle( const Point& _p ):p(new Point(_p)){}
Handle& operator=( const Handle& _h ){
//reattach作用表现在这里
if( u.reattach( _h.u ) )
delete p;
p = _h.p;
return *this;
}
~Handle(){
//only的作用
if( u.only() )
delete p;
}
//解决了上面说到的好处之一
Handle& x( int _x ){
//是否是唯一一个
if( u.makeonly() )
p = new Point(*p);
p->x(_x);
return *this;
}
private:
Point* p;
UseCount u;
};
C++沉思录句柄3
最新推荐文章于 2023-06-02 16:02:33 发布