之前文章中实现的写时复制,句柄类中引用计数和T类型指针是分开的,这里换一种方式来处理,将引用计数和T类型指针视为一个整体,当做句柄类模板参数。先对上节中的引用计数进行改造:

这个版本的UseCount和之前的版本差别很大,从析构函数可以看出(纯虚函数),它是基于引用计数来共享的值对象的基类,需要注意的部分:

 1 class CUseCount 
 2 { 
 3 public: 
 4     CUseCount(); 
 5     CUseCount(const CUseCount&);
 6     CUseCount& operator=(const CUseCount&);
 7     virtual ~CUseCount() = 0; 
 8  
 9     void markUnshareable();
10     bool isShareable() const;
11     bool isShared() const;
12     
13     void addReference();
14     void removeReference();
15  
16 private:
17     int refCount;    //注意这里非int指针
18     bool shareable;    //是否是共享状态
19 };
20 
21 CUseCount::CUseCount():refCount(0), shareable(true)
22 {} 
23  
24 CUseCount::CUseCount(const CUseCount& u):refCount(0), shareable(true)
25 {}
26 
27 CUseCount& CUseCount::operator=(const CUseCount& u)
28 {
29     return *this;
30 }
31 
32 CUseCount::~CUseCount() 
33 {} 
34 
35 void CUseCount::markUnshareable()         
36 {          
37     shareable = false;          
38 }
39         
40 bool CUseCount::isShareable() const
41 {
42     return shareable;         
43 }
44    
45 bool CUseCount::isShared() const
46 {         
47     return refCount > 1;         
48 }
49 
50 void CUseCount::addReference() 
51 {
52     ++refCount;
53 }
54 
55 void CUseCount::removeReference()         
56 {          
57     if(--refCount == 0)
58         delete this;         
59 }
View Code

相关文章: