#include <iostream>
using namespace std;
class String
{
public:
String(const char* str = "")
:_str(new char[strlen(str) + 5])
{
strcpy(_str+4 ,str);
_GetRefCount(_str) = 1;
}
String(String& s)
:_str(s._str)
{
++s._GetRefCount(_str);
}
String& operator=(const String& s)
{
if(this != &s)
{
this->_Release();
//strcpy(_str,s._str);
_str = s._str;
++_GetRefCount(_str);
}
return *this;
}
char& operator[](size_t index)
{
if(_GetRefCount(_str) > 1)
{
_Release();
char* tmp = new char[strlen(_str) + 5];
strcpy(tmp + 4, _str);
_GetRefCount(tmp) = 1;
_str = tmp;
}
return _str[index];
}
~String()
{
_Release();
}
private:
int& _GetRefCount(char* str)
{
return *(int*)(str - 4);
}
void _Release()
{
if(--_GetRefCount(_str) == 0)
{
delete[] (_str-4);
}
}
friend ostream& operator<<(ostream& os, const String& s);
private:
char* _str;
};
ostream& operator<<(ostream& os, const String& s)
{
os<<"当前计数 "<<*(int*)(s._str - 4)<<endl;
os<<s._str + 4;
return os;
}
void Test1()
{
String s1("sfdvfv");
cout<<"s1 "<<s1<<endl;
/*String s2(s1);*/
//cout<<s2<<endl;
String s3(s1);
//s3 = s1;
cout<<"s3 "<<s3<<endl;
s3[2] = 'm';
cout<<"s3 "<<s3<<endl;
}
int main()
{
Test1();
return 0;
}String Copy_on_write
最新推荐文章于 2024-06-07 13:45:16 发布
本文详细介绍了如何使用C++智能指针实现字符串类的构造、复制、赋值和索引操作,通过成员函数和友元函数实现字符串计数和输出,并展示了对象析构过程中的资源释放。
3429

被折叠的 条评论
为什么被折叠?



