1. 程式人生 > >c++沈思錄 學習筆記 第六章 句柄(引用計數指針雛形?)

c++沈思錄 學習筆記 第六章 句柄(引用計數指針雛形?)

return 指針 使用權 -- play cpp open end 使用

一個簡單的point坐標類

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;
};

將handle 綁定到其上 進行一層封裝

通過handle控制那些操作可以公開 那些操作私有 阻止用戶對point的地址的操作

更重要的是提供 point的引用計數 將多個handle綁定到ppint上 當全部釋放對point的使用權時

才進行釋放point的操作

那麽增加兩個類

一個引用計數類 class UPoint

class UPoint {
friend class Handle;
Point p;
int u;

UPoint() :u(1) {}
UPoint(int x, int y) :p(x, y), u(1) {}
UPoint(const Point& p0):p(p0),u(1){}
};

一個是handle句柄類 包含UPoint的指針 構造和析構的時候會將計數+1

當計數到0 則釋放指針內存

class Handle {
public:
Handle();
Handle(int, int);
Handle(const Point&);
Handle(const Handle&);
Handle& operator=(const Handle&);
~Handle();
int x()const;
Handle& x(int);
int y()const;
Handle& y(int);
private:
UPoint* up;

};

全部代碼如下:

技術分享
 1 // sample0.cpp: 定義控制臺應用程序的入口點。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 
 7 class Point {
 8 public:
 9     Point():xval(0),yval(0){}
10     Point(int x,int y):xval(x),yval(y){}
11     int x()const { return xval; }
12     int y()const { return yval; }
13     Point& x(int xv) { xval = xv; return *this; }
14     Point& y(int yv) { yval = yv; return *this; }
15 private:
16     int xval, yval;
17 };
18 
19 class UPoint {
20     friend class Handle;
21     Point p;
22     int u;
23 
24     UPoint() :u(1) {}
25     UPoint(int x, int y) :p(x, y), u(1) {}
26     UPoint(const Point& p0):p(p0),u(1){}
27 };
28 
29 class Handle {
30 public:
31     Handle();
32     Handle(int, int);
33     Handle(const Point&);
34     Handle(const Handle&);
35     Handle& operator=(const Handle&);
36     ~Handle();
37     int x()const;
38     Handle& x(int);
39     int y()const;
40     Handle& y(int);
41 private:
42     UPoint* up;
43 };
44 
45 Handle::Handle() :up(new UPoint) {}
46 Handle::Handle(int x, int y) : up(new UPoint(x, y)) {}
47 Handle::Handle(const Point& p) : up(new UPoint(p)) {}
48 
49 Handle::~Handle() {
50     if (up->u == 0)
51         delete up;
52 }
53 
54 Handle::Handle(const Handle& h) :up(h.up) { ++up->u; }
55 Handle& Handle::operator=(const Handle& h) {
56     ++h.up->u;
57     if (--up->u == 0) {
58         delete up;
59     }
60     return *this;
61 }
62 
63 int Handle::x()const { return up->p.x(); }
64 int Handle::y()const { return up->p.y(); }
65 
66 Handle& Handle::x(int x0)
67 {
68     up->p.x(x0);
69     return *this;
70 }
71 
72 Handle& Handle::y(int y0) {
73     up->p.y(y0);
74     return *this;
75 }
76 
77 
78 int main()
79 {
80     Handle h;
81     std::cout << h.x() << " " << h.y() << std::endl;
82     return 0;
83 }
View Code

c++沈思錄 學習筆記 第六章 句柄(引用計數指針雛形?)