标签:写时拷贝
#include<iostream>
using namespace std;
class String
{
public:
String(const char*str = "")
:_str(new char[strlen(str) + 1])
,_pRefCount(new int(1))
{
strcpy(_str, str);
}
String(const String&s)
:_str(s._str)
,_pRefCount(s._pRefCount)
{
++(*_pRefCount);
}
void _Release()
{
if (--(*_pRefCount)==0 &&_str)
{
delete[]_str;
delete _pRefCount;
cout << "delete" << endl;
}
}
String& operator=(const String&s)
{
if (this != &s)
{
this->_Release();
_str = s._str;
_pRefCount = s._pRefCount;
++(*_pRefCount);
}
return*this;
}
char& operator[](size_t index)
{
if (*_pRefCount > 1)
{
--(*_pRefCount);
char* tmp = new char[strlen(_str) + 1];
strcpy(tmp, _str);
_str = tmp;
_pRefCount = new int(1);
}
return _str[index];
}
friend ostream& operator<<(ostream& os, const String&s);
private:
char* _str;
int* _pRefCount;
};
ostream& operator<<(ostream& os, const String&s)
{
os << s._str;
return os;
}
void Test1()
{
String s1("abcd");
String s2(s1);
cout << "s1:" << s1 << endl;
cout << "s2:" << s2 << endl;
}
void Test2()
{
String s1("abcde");
String s2;
s2 = s1;
String s3(s2);
cout << "s1:" << s1 << endl;
cout << "s2:" << s2 << endl;
cout << "s3:" << s3 << endl;
}
void Test3()
{
String s1("abcde");
String s2(s1);
cout << "s1:" << s1 << endl;
cout << "s2:" << s2 << endl;
s2[0] = ‘x‘;
s2[4] = ‘x‘;
cout << "s1:" << s1 << endl;
cout << "s2:" << s2 << endl;
}
int main()
{
//Test1();
//Test2();
Test3();
return 0;
}
标签:写时拷贝
原文地址:http://10622551.blog.51cto.com/10612551/1692763