class String
{
public:
String(const char *str = "")
:_str(new char[strlen(str) + 1 + 4])
{
cout << "Sring()" << endl;
_str += 4; //前4个字节用来存放引用计数
GetCount() = 1; //引用计数的初始值设置成1
strcpy(_str, str);
}
String(String& s)
:_str(s._str)
{
cout << "Sring(String&)" << endl;
GetCount()++;
}
String& operator=(String& s)
{
cout << "Sring& operator=" << endl;
if (this != &s)
{
Release();
_str = s._str;
GetCount()++;
}
return *this;
}
~String()
{
cout << "~Sring()" << endl;
Release();
}
public:
char& operator[](size_t index)
{
if (GetCount() == 1) //如果计数器为1,则直接返回
{
return _str[index];
}
GetCount()--;
char *tmp = _str;
_str = new char[strlen(tmp) + 1 + 4];
_str += 4;
strcpy(_str, tmp);
GetCount() = 1;
return _str[index];
}
private:
int& GetCount()
{
return *(int *)(_str - 4);
}
void Release()
{
if (--GetCount() == 0)
{
cout << "释放" << endl;
delete[](_str - 4); //注意释放的时候还有 存放引用计数的4个字节
_str = NULL;
}
}
private:
char *_str;
};
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有