《C++沉思录》-第六章-句柄:第一部分
来源:互联网 发布:vb循环语句 编辑:程序博客网 时间:2024/04/28 00:47
第五章介绍的代理将会复制所代理的对象,就像复制代理一样。句柄允许保持代理的多态行为的同时,还可以避免进行不必要的复制。
句柄类(handle class)也称为 智能指针(smart pointer)。
一个简单的类:
class Point{public: Point():m_x(0),m_y(0){} Point(int x,int y):m_x(x),m_y(y){} int x()const {return m_x;} int y()const { return m_y;} Point& x(int x) { m_x = x; return *this;} Point& y(int y) { m_y = y; return *this;}private: int m_x; int m_y;};
句柄:
class UPoint{ //所有成员都是私有 friend class Handle; Point p; int u;//用于计数 UPoint():u(1){} UPoint(const Point&pv):p(pv),u(1) {} UPoint(int x,int y):p(x,y),u(1) {} UPoint(const UPoint &up):p(up.p),u(1) {}};
class Handle{public: Handle(): up(new UPoint) {} Handle(int x,int y): up(new UPoint(x,y)) {} Handle(const Point&p): up(new UPoint(p)) {} Handle(const Handle &h) : up(h.up) { //指向相同的UPoint对象,引用计数增加1 ++up->u; } Handle& operator=(const Handle &h) { ++h.up->u; if (--up->u == 0) {//引用计数-1,如果为0,删除UPoint对象 delete up; } up = h.up; return *this; } ~Handle() { //引用计数为0时,就删除UPoint对象 if (--up->u == 0) { delete up; } } int x() const{ return up->p.x(); } int y() const{ return up->p.y(); } /*(1)指针语义,互相影响*/ Handle& x(int x0) { up->p.x(x0); return *this; } Handle& y(int y0) { up->p.y(y0); return *this; } /*(2)值语义,互不影响,写时复制 Handle& x(int xv) { allocUp(); up->p.x(xv); return *this; } Handle& y(int yv) { allocUp(); up->p.y(yv); return *this; }*/private: UPoint *up; /*(2)值语义,互不影响*/ void allocUp() { //如果为1,说明不是唯一的,那就要复制对象 //使得引用计数为1 if (up->u != 1) { --up->u; up = new UPoint(up->p); } }};
- 《C++沉思录》 第六章 句柄 第一部分
- 《C++沉思录》-第六章-句柄:第一部分
- C++沉思录读书笔记(6章)-句柄:第一部分
- 《c++沉思录》第七章 句柄:第二部分
- C++沉思录读书笔记(7章)-句柄:第二部分
- C++沉思录读书笔记(7章)-句柄:第二部分
- 《C++沉思录》-第七章-句柄:第二部分
- C++沉思录句柄C6
- C++沉思录句柄2
- C++沉思录句柄3
- 第一哲学沉思录
- C++沉思录-第6章 句柄
- 沉思录句柄类之二
- C++沉思录句柄类总结1
- 句柄-摘自《C++沉思录》Andrew Koenig
- c++沉思录中代理类和c++primer中句柄类的对比
- C++沉思录-第7章 句柄二 引用计数的分离
- 表达式 《c++沉思录》第八章
- 第二讲(类的学习)
- 深入浅出Windows PE(一) PE文件头
- Spring中Quartz的配置
- Linux红黑树(二)——访问节点
- 第十五周 输出多科成绩
- 《C++沉思录》-第六章-句柄:第一部分
- 屏幕开发-屏幕文本的翻译
- php中使用伪静态
- 问题之--过滤器
- 条款03:尽可能的使用const
- Mac OS X “to open Eclipse, you need a Java SE 6 runtime”问题解决
- Mac下编译Android源码(OSX10.9 Mavericks)
- 数据库中聚集索引和非聚集索引区别
- sd卡启动linux 以及烧写内核