C++沉思录句柄2

//改进句柄类。
//将问题拉近核心
//问题:重复Point操作。
//		继承无效了。


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 UPoint{
//	friend class Handle;
//	Point p;
//	int u;
//
//	//而且重复的了Point的接口操作
//	//这些接口操作更本不需要。
//	UPoint(): u(1){}
//	UPoint( int x, int y ): p(x, y), u(1){}
//	UPoint( const Point& _p ):p(_p),u(1){}
//};

//解决方案1:
//将Point和计数器都放到Handle中


class Handle{
	Point*  p;		//可以解决Point类继承问题
	int*	u;		//这样所有 有关联的 Handle对象就可以只拥有一个计数器了

public:
	Handle(  ):p(new Point(0, 0)), u(new int(1)){}
	Handle( const Point& _p):p(new Point(_p)), u(new int(1)){}
	Handle( const Handle& _h):p(new Point(*_h.p)), u(_h.u){
		++*_h.u;
	}
	Handle& operator=( const Handle& _h ){
		++*_h.u;
		if( --*u == 0 )
			delete p;
		p = _h.p;
		u = _h.u;
		return *this;
	}
	~Handle(){

		//成对的删除
		//以及上面成对的创建。
		//为了理清关系,所以将抽象化计数器类。
		//抽象计数器类将提供几个好处
		//第二个方案
		if( --*u == 0 ){
			delete p;
			delete u;
		}
	}


	//提供Point接口操作
	//如果感觉在Handle中提供Point类接口操作很别扭。
	//可以改成
	//Type operator*()
	//Type operator->()
	//但是这样就暴露了内部p的属性和接口,偏离了句柄核心
	//用户可以控制p内存的释放
	//改成const type operator*() const
	//也不行,因为不能修改常量对象,导致操作接口无意义了

	int x(  )const{
		return p->x;
	}
	int y(  )const{
		return p->y;
	}

	void x( int _x ){
		p->x( _x );
	}
	void y( int _y ){
		p->y( _y );
	}
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值