string类的浅拷贝是错误的做法,错误在于会共用一块空间,释放时候会出现错误。 这里不写了。
String type deep copy _ common
class String
{
public:
String(const char* pstr = "")
{
if(NULL == pstr)
{
_pstr = new char[1];
*_pstr = '\0';
}
else
{
_pstr = new char[strlen(pstr)+1];
strcpy(_pstr , pstr);
}
}
String(const String& t)
{
_pstr = new char[strlen(t._pstr)+1];
strcpy(_pstr , t._pstr);
}
String& operator=(const String& t ) //
{
if(this != &t) // 判断是不是自己给自己赋值 如果不是
{
char *ptemp = new char[strlen(t._pstr)+1]; // 创建一个新的指针, 去指向一个new出来的新空间(大小等于被拷贝的大小)
strcpy(ptemp,t._pstr); // 这块是两个指针的复制,因为ptemp有自己的空间,不存在共用一块空间的问题。
delete[] _pstr; // 释放以前 _pstr的空间
_pstr = ptemp; // 让_pstr的指向指向了 要被拷贝的空间(他已经被ptemp所复制)
} // 疑问,为什么不直接指向和释放? 这里和所传的引用有关
return *this;
}
~String()
{
if(NULL != _pstr)
{
delete[] _pstr;
_pstr = NULL;
}
}
private:
char* _pstr;
};
int main()
{
String s1("hello");
String s2(s1);
String s3 = s2;
return 0;
}
strring type deep copy _ simple
class String
{
public:
String(const char* pstr = "")
{
if(NULL == pstr)
{
_pstr = new char[1];
*_pstr = '\0';
}
else
{
_pstr = new char[strlen(pstr)+1];
strcpy(_pstr , pstr);
}
}
String(const String& t)
:_pstr(new char[strlen(t._pstr)+1])
{
//_pstr = new char[strlen(t._pstr)+1];
strcpy(_pstr , t._pstr);
}
String& operator=( String t ) //没有传const ,这个值要改变,没有传& 是因为是给他的临时拷贝去改变, 这个临时拷贝在生命周期结束 后会自动析构掉
{
std::swap(_pstr,t._pstr); //交换指向就可以了。都不用delete了。
/*if(this != &t)
{
char *ptemp = new char[strlen(t._pstr)+1];
strcpy(ptemp,t._pstr);
delete[] _pstr;
_pstr = ptemp;
}
return *this;*/
}
~String()
{
if(NULL != _pstr)
{
delete[] _pstr;
_pstr = NULL;
}
}
private:
char* _pstr;
};
int main()
{
String s1("hello");
String s2(s1);
String s3 = s2;
return 0;
}
要注意的是,每次new 一个新的空间时候,要去有一个指针指向它。
common & simple 的不同在于重载“ = ” 的不同