——将句柄与使用者信息分离,以类的形式存在
1. 计数类:控制计数的类,被嵌入句柄来使用,实现功能分离
2. 实现代码
1 #include <iostream> 2 using namespace std; 3 4 // 计数部分 5 class UseCount 6 { 7 private: 8 int *p; 9 UseCount& operator=(const UseCount&); 10 public: 11 UseCount():p(new int(1)){} 12 UseCount(const UseCount& u):p(u.p){*p++;} 13 ~UseCount(){if (--*p==0) delete p;}; 14 15 bool only(); 16 bool reattach(const UseCount&); 17 bool makeonly(); 18 }; 19 20 UseCount& UseCount::operator=(const UseCount& u) 21 { 22 reattach(u); 23 return *this; 24 } 25 26 bool UseCount::only() 27 { 28 // 检测句柄是否唯一 29 return *p==1; 30 } 31 32 bool UseCount::reattach(const UseCount& u) 33 { 34 // 替换句柄指向的对象,当被替换的是唯一的句柄时返回true 35 ++*u.p; 36 if (--*p==0) 37 { 38 delete p; 39 p = u.p; 40 return true; 41 } 42 p = u.p; 43 return false; 44 } 45 46 bool UseCount::makeonly() 47 { 48 // 使该句柄被分离,被替分离的如果是唯一的句柄,那么分离失败 49 if (*p==1) 50 return false; 51 --*p; 52 p = new int(1); 53 return true; 54 } 55 56 // 句柄指向的类 57 class digit 58 { 59 private: 60 int x; 61 public: 62 digit(){} 63 digit(int x_):x(x_){} 64 int xx() {return x;} 65 void xx(int x_){x = x_;} 66 }; 67 68 // 句柄 69 class handle 70 { 71 private: 72 digit *u; 73 UseCount p; 74 public: 75 handle():u(0){} 76 handle(int x):u(new digit(x)){} 77 handle(const digit &dg):u(new digit(dg)){} 78 handle(const handle &han):u(han.u),p(han.p){} 79 handle& operator=(const handle& han); 80 // 存取函数 81 int x() {return u->xx();} 82 handle& x(int x_); 83 ~handle(){if (p.only()) delete(u);} 84 }; 85 86 handle& handle::operator=(const handle& han) 87 { 88 if (p.reattach(han.p)) 89 delete(u); 90 u = han.u; 91 return *this; 92 } 93 94 handle& handle::x(int x_) 95 { 96 if (p.makeonly()) 97 u = new digit(*u); 98 u->xx(x_); 99 return *this; 100 } 101 102 int main() 103 { 104 handle han1(3); 105 handle han2 = han1; 106 handle han3 = han2; 107 printf("han3: %d\n", han3.x()); 108 han3.x(5); 109 printf("han2: %d\n", han2.x()); 110 printf("han3: %d\n", han3.x()); 111 return 0; 112 }
输出结果为:han3: 3
han2: 3
han3: 5