在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
C++简单实现对象引用计数示例 1 #include <iostream> 2 #include <stdio.h> 3 4 using namespace std; 5 6 class String { 7 public: 8 String(const char *pdata); 9 String(const String &rhs); 10 String &operator = (const String &rhs); 11 ~String(); 12 13 public: //应该使用private,但为了演示的目的而使用public 14 //内部类 15 class StringValue { 16 public: 17 StringValue(const char *pdata); 18 ~StringValue(); 19 public: 20 int refCount; 21 char *data; 22 }; 23 24 StringValue *value;//所有的引用对象均共享唯一一个value,value里面实际存储data和引用次数 25 }; 26 27 String::StringValue::StringValue(const char *pdata):refCount(1) { 28 data = new char[strlen(pdata) + 1]; 29 strcpy(data,pdata); 30 } 31 32 String::StringValue::~StringValue() { 33 delete [] data; 34 } 35 36 String::String(const char *pdata) : value(new StringValue(pdata)) {} 37 38 String::String(const String &rhs) {//要对引用加1 39 value = rhs.value; 40 (value->refCount)++;//所有指向同一段data的对象的引用加1 41 } 42 43 String &String::operator =(const String &rhs) { 44 if (value == rhs.value)//注意,不是this == &rhs 45 return *this; 46 if(--value->refCount == 0) 47 { 48 printf("operator =[delete value] value->refCount=%d\n",value->refCount); 49 delete value; 50 } 51 52 value = rhs.value; 53 ++(value->refCount); 54 55 return *this; 56 } 57 58 String::~String() { 59 if ( (--value->refCount) == 0 ) 60 { 61 printf("~String():[delete value] value->refCount=%d\n",value->refCount); 62 delete value; 63 } 64 else 65 { 66 printf("~String(): value->refCount=%d\n",value->refCount); 67 } 68 } 69 70 void test() { 71 String ss("ssss"); 72 printf("ss.value->refCount=%d\n",ss.value->refCount); 73 String s1 = ss; 74 printf("s1.value->refCount=%d\n",s1.value->refCount); 75 printf("ss.value->refCount=%d\n",ss.value->refCount); 76 String s2("dddd"); 77 printf("s2.value->refCount=%d\n",s2.value->refCount); 78 s2 = ss; 79 printf("s2.value->refCount=%d\n",s2.value->refCount); 80 printf("ss.value->refCount=%d\n",ss.value->refCount); 81 } 82 83 int main() { 84 test(); 85 } 运行结果如下: ss.value->refCount=1
转自:http://blog.csdn.net/chinawangfei/article/details/50680574 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论