拷贝可以概括性的分为以下几类
1 s1和s2分别有它们自己的值,我们需要将s1的对应的空间释放掉然后赋给其s2的值
2 s1和s2分别有它们自己的值,但是s1还有其他别名,我们需要引入计数,为了防止其在析构时程序崩溃(多次释放同一块内存空间)。如图
3 s1和s2对应同一块内存空间,那么我们就不需要赋值了。
//构造函数
String(const char* ptr = " ")
{
if(ptr == NULL)
{
_ptr = new char[1];
_pcount = 1;
*_ptr = '\0';
}
else
{
_pcount = 1;
_ptr = new char[strlen(ptr)+1];
strcpy(_ptr,ptr);
}
}
//赋值运算符重载
String& operator==(const string s)
{
if(_str!=s._str)
{
if(--(*refCountPtr)==0)
{
delete[]_str;
delete _refCountPtr;
}
_str=s._str;
_refCountPtr=s._refCountPtr
(*refCountPtr)++;
}
return *this;
}
//拷贝构造
String(String& s)
:_ptr(s._ptr)
,_pcount(s._pcount)
{
_pcount++;
}
//析构函数
~String()
{
if((0 == --_pcount) && _ptr!= NULL)
{
delete[]_ptr;
//delete _pcount;
_ptr = NULL;
}
}