#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
最新推荐文章于 2017-09-04 19:09:54 发布