<span style="font-size:24px;">#include<iostream>
using namespace std;
class String
{
public:
//构造函数
String(const char* str="")
:_str(new char[strlen(str)+1])
, _CountRef(new int(1))
{
strcpy(_str, str);
}
//拷贝构造
String(const String& s)
:_str(s._str)
, _CountRef(s._CountRef)
{
++(*_CountRef);
}
//赋值操作符的重载
String& operator=(const String& s)
{
if (this != &s)
{
if (--(*_CountRef) == 0 && _str)
{
delete[] _str;
delete _CountRef;
}
_str = s._str;
_CountRef = s._CountRef;
++(*_CountRef);
}
return *this;
}
//析构函数
~String()
{
if (--(*_CountRef) == 0 && _str)
{
delete[] _str;
delete _CountRef;
}
}
//[]操作符的重载 写时拷贝
char& operator[](size_t index)
{
if ((*_CountRef) > 1)
{
--(*_CountRef);
char* tmp = new char[strlen(_str) + 1];
strcpy(tmp, _str);
_str = tmp;
_CountRef = new int(1);
}
return _str[index];
}
private:
char* _str;
int* _CountRef;//引用计数
};
//测试拷贝构造
void Test1()
{
String s1("abcd");
String s2(s1);
String s3(s2);
}
//测试赋值操作符的重载
void Test2()
{
String s1("abcd");
String s2;
String s3(s2);
s2 = s1;
}
//测试写时拷贝
void Test3()
{
String s1("abcd");
String s2(s1);
s2[0] = 'x';
}
int main()
{
Test1();
Test2();
Test3();
return 0;
}</span>
【C++】写时拷贝COW
最新推荐文章于 2022-01-10 20:08:47 发布