句柄与引用计数实现

 

// 句柄二.cpp : 定义控制台应用程序的入口点。
//句柄类二,将引用计数设计为一个特定的类来实现,在程序中要注意引用计数的操作和point的类的实例操作的一致性,
//为此,在计数类中添加了相应的函数来实现,句柄就是point类的代理操作,外加了引用计数来实现复制操作。也时所说的
//智能指针,其取名其实就是通过他的实现技术上的,程序中同样实现的用时复制的技术。这样操作handle类就像操作point
//类一样,并且不用考虑怎样来实现的
#include "stdafx.h"


#include <iostream>
using namespace std;
#include <windows.h>

class point
{
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 xv){xval=xv;return *this;}
 point & y(int yv){yval=yv;return *this;}
private:
 int xval,yval;
};
class usercount
{
public:
 usercount();
 usercount(usercount&);
// usercount& operator=(const usercount&);
 bool only(){ return(*c==1);}
 bool retattch(const usercount&);
 bool takeonly();
 ~usercount();
private:
 int *c;
 usercount& operator=(const usercount&);

};
usercount::~usercount()
{
 if(--*c==0)
  delete c;
}
usercount::usercount():c(new int(1)){}
usercount::usercount(usercount &u){if(--*c==0) delete c;c=u.c;}
bool usercount::takeonly()
{
 if(*c==1)
  return false;
 --*c;
 c=new int(1);
 return true;

}
bool usercount::retattch(const usercount & u)
{
 ++*u.c;
 if(--*c==0)
 {
  delete c;
  c=u.c;
  return true;
 }
 c=u.c;
 return false;

}


class handle
{
public:
 handle();
 handle(int,int);
 handle(const handle&);
 handle &operator=(const handle &);
 ~handle();
 int x()const;
 int y()const;
 handle &x(int);
 handle &y(int);
private:
 point *p;
 usercount u;

};
handle::handle():p(new point){}
handle::handle(int x,int y):p(new point(x,y)){}
handle::handle(const handle & h):p(h.p){u.retattch(h.u);}
handle::~handle()
{
 if(u.only())
  delete p;
}
handle &handle::operator =(const handle & h)
{
 if(u.retattch(h.u))
 {
  delete p;
  p=h.p;
 }
 p=h.p;
 return *this;
}
int handle::x() const {return p->x();}
int handle::y()const  {return p->y();}

//指针模式赋值,指向同一个变量,改变时,同时改变变量的值;
//handle &handle::x(int x0){up->p.x(x0);return *this;}
//handle &handle::y(int y0){up->p.y(y0);return *this;}

//值模式赋值,写时复制,当改变多个指针指向的变量时,
//此时复制一个新的变量,并且对复制的变量进行更改;
//而原来的变量值不变,减小开销
handle &handle::x(int x0)
{
 if(u.takeonly())
  p=new point(*p);
 p->x(x0);
 return *this;

}
handle &handle::y(int y0)
{
 if(u.takeonly())
  p=new point(*p);
 p->y(y0);
 return *this;
}

int _tmain(int argc, _TCHAR* argv[])
{
 handle h(3,6);
 handle hh=h;
 hh.x(5);
 cout<<h.x()<<"fengqiang"<<hh.x()<<endl;

 return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值