c++的引用计数与写时复制
来源:互联网 发布:拉伸法测杨氏模量数据 编辑:程序博客网 时间:2024/05/01 03:41
最近看了C++沉思录,了解一下句柄类,其中的引用计数,写时复制技术很值得学习,特将它摘抄下来,希望它对大家也有用。
//原始类
class CPoint
{
public:
CPoint(): xval(0), yval(0)
{}
CPoint(int x, int y): xval(x), yval(y)
{}
int x() const
{
return xval;
}
int y() const
{
return yval;
}
CPoint& x(int xv)
{
xval = xv;
return *this;
}
CPoint& y(int yv)
{
yval = yv;
return *this;
}
private:
int xval;
int yval;
};
//引用计数类
class UseCount
{
public:
UseCount();
UseCount(const UseCount&);
bool reattach(const UseCount&);
~UseCount();
bool only();
bool makeOnly();
int getCount();
private:
//禁止赋值
UseCount& operator=(const UseCount&);
int* p;
};
UseCount::UseCount(): p(new int(1))
{}
UseCount::UseCount(const UseCount& u): p(u.p)
{
++*p;
}
//返回值为true 需要删除宿主类的赋值
bool UseCount::reattach(const UseCount& u)
{
++*u.p;
if (--*p == 0)
{
delete p;
p = u.p;
return true;
}
p = u.p;
return false;
}
//写时复制
bool UseCount::makeOnly()
{
if (*p == 1)
{
return false;
}
--*p;
p = new int(1);
return true;
}
int UseCount::getCount()
{
return *p;
}
UseCount::~UseCount()
{
if (--*p == 0)
{
delete p;
}
}
//确保只有一个引用
bool UseCount::only()
{
return *p == 1;
}
//句柄类
class Handle
{
public:
Handle();
Handle(int, int);
Handle(const CPoint& p0);
Handle(const Handle&);
Handle& operator=(const Handle&);
~Handle();
int x() const;
Handle& x(int);
int y() const;
Handle& y(int);
int getCount();
private:
CPoint* p;
UseCount u;
};
Handle::Handle(): p(new CPoint)
{
}
Handle::Handle(int x, int y): p(new CPoint(x, y))
{
}
Handle::Handle(const CPoint& p0): p(new CPoint(p0))
{
}
Handle::Handle(const Handle& h): u(h.u), p(h.p)
{
}
Handle& Handle::operator=(const Handle& h)
{
if (u.reattach(h.u))
{
delete p;
}
p = h.p;
return *this;
}
Handle::~Handle()
{
if (u.only())
{
delete p;
}
}
int Handle::getCount()
{
return u.getCount();
}
int Handle::x() const
{
return p->x();
}
Handle& Handle::x(int x0)
{
if (u.makeOnly())
{
p = new Point(*p);
}
p->x(x0);
return *this;
}
- 47-引用计数与写时复制
- c++的引用计数与写时复制
- PHP内核探索:引用计数与写时复制
- string类的写时拷贝与引用计数
- string类的写时拷贝与引用计数
- 写时拷贝与引用计数
- PHP变量引用计数,写时复制详解
- php 垃圾回收机制 写时复制和引用计数
- PHP源码分析-变量的引用计数、写时复制(Reference counting & Copy-on-Write)
- 缓式评估、写时复制及引用计数的关系
- 引用计数的写时拷贝
- 引用计数的写时拷贝
- String-引用计数的写时拷贝
- 引用计数的写时拷贝
- string引用计数的写时拷贝
- 理解php内核的 引用计数器与写时复制
- PHP中引用的详解(引用计数、写时拷贝)
- PHP中引用的详解(引用计数、写时拷贝)
- Calendar
- 程序员面试可能会问到的问题
- 在Eclipse中安装SWT插件
- Applet数字签名
- 事务码备忘
- c++的引用计数与写时复制
- Robust Definition
- 还君明珠
- B2C被“传统”了?
- 开门
- ERwin r7 的注册码
- GIS研究生的19个方向
- 带儿子扫墓真是件既累人又有趣的事
- 今天学到yum的新参数,解决了编译MPLAY出现的The GUI requires GTK devel packages