写时拷贝技术是通过"引用计数"实现的,在分配空间的时候多分配4个字节,用来记录有多少个指针指向块空间,当有新的指针指向这块空间时,引用计数加一,当要释放这块空间时,引用计数减一(假装释放),直到引用计数减为0时才真的释放掉这块空间。当有的指针要改变这块空间的值时,再为这个指针分配自己的空间(注意这时引用计数的变化,旧的空间的引用计数减一,新分配的空间引用计数加一)。
写时拷贝实现String类
代码实现:
#include <iostream> using namespace std; #pragma warning(disable:4996) class String { public: //构造函数 String(char* ptr = NULL):_str(new char[strlen(ptr) + 5]) { _str = _str + 4; strcpy(_str, ptr); getCount(_str) = 1; } //拷贝构造函数 String(const String& rhs):_str(rhs._str) { ++getCount(_str); } String& operator=(const String& rhs) { if (this != &rhs) { Release(); _str = rhs._str; ++getCount(_str); } return *this; } //重载[]运算符 char& operator[](int index) { if (getCount(_str) > 1) { --getCount(_str); char* tmp = new char[strlen(_str) + 5]; tmp = tmp + 4; getCount(tmp) = 1; strcpy(tmp, _str); _str = tmp; } return _str[index]; } //析构函数 ~String() { Release(); } char* c_str() { return _str; } private: void Release() { if (--getCount(_str) == 0) { delete[](_str - 4); } } int& getCount(char* ptr) { return *(int*)(ptr - 4); } char* _str; }; int main() { String s1("hello"); String s2(s1); printf("s1.address:%x\n", s1.c_str()); printf("s2.address:%x\n", s2.c_str()); s2[0] = 's'; printf("s1.address:%x\n", s1.c_str()); printf("s2.address:%x\n", s2.c_str()); s1[1] = 'w'; printf("s1.address:%x\n", s1.c_str()); printf("s2.address:%x\n", s2.c_str()); return 0; }
运行结果: