String类的写时拷贝
#include#include using namespace std;class String{public: friend ostream& operator <<(ostream &os, String &str); String(char *str = "") :_str(new char[strlen(str) + 1 + 4]) { _str = _str + 4; getCount() = 1; strcpy(_str, str); } String(String &str) :_str(str._str) { ++getCount(); } String &operator=(String &str) { if (this != &str) { release(); _str = str._str; ++getCount(); } return *this; } char &operator[](int index) { assert(index >= 0); assert(index<(int)strlen(_str)); if (getCount()>1) { --getCount(); char *temp = new char[strlen(_str) + 4 + 1]; strcpy(temp + 4, _str); _str = temp + 4; getCount() = 1; } return _str[index]; } ~String() { release(); }private: void release() { if (_str&&(--getCount() == 0)) { delete[](_str-4); _str = NULL; } } int &getCount() { return *(int*)(_str - 4); } char *_str;};ostream &operator<<(ostream &os, String &str){ os << str._str; return os;}void test1(){ String str1("hello "); String str2(str1); String str3("world"); String str4(str3); str1[0] = 'c'; str1[1] = 'h'; str1[2] = 'a'; str1[3] = 'n'; str1[4] = 'g'; str1[5] = 'e'; str2 = str3; cout << str1 << endl; cout << str3 << endl;}int main(){ test1(); system("pause"); return 0;}