class String
{
public:
String(const char* str="")
:_str(new char[strlen(str) + 5])
{
cout << "String()" << endl;
_str += 4;
_GetRefCount(_str) = 1;
strcpy(_str, str);
}
String(const String& s)
:_str(s._str)
{
++_GetRefCount(_str);
}
~String()
{
cout << "~String()" << endl;
_Release();
}
String& operator=(const String& s)
{
if (_str != s._str)
{
_Release();
_str = s._str;
++_GetRefCount(_str);
}
return *this;
}
char& operator[](int index)//不写现代写法
{
if (_GetRefCount(_str) > 1)
{
char* tmp = new char[strlen(_str) + 5];
tmp += 4;
_GetRefCount(tmp) = 1;
strcpy(tmp, _str);
--_GetRefCount(_str);
_str = tmp;
}
return _str[index];
}
int GetRefCount()
{
return _GetRefCount(_str);
}
char* C_str()
{
return _str;
}
private:
int& _GetRefCount(char* str)
{
return *(int *)(str - 4);
}
void _Release()
{
if (--_GetRefCount(_str) == 0)
{
delete[] (_str-4);//注意指针的位置
}
}
private:
char* _str;
}
String的浅拷贝
最新推荐文章于 2023-02-10 18:58:53 发布