代码如下:
//传统写法
//s2(s1)
string(const string& s)
:_str(new char[strlen(s._str)+1])
{
strcpy(_str, s._str);
}
//s2=s1
string& operator=(const string& s)
{
if (this != &s) //s1 !=s1
{
delete[] _str;
_str = new char[strlen(s._str) + 1];
strcpy(_str, s._str);
}
return *this;
}
其中delete的原因是下面又要开辟新的空间,把旧的空间释放
可以理解为自己做饭
代码如下:
//现代写法
//s2(s1)
string(const string& s)
:_str(nullptr)
{
string temp(s._str);
swap(_str, temp._str);
swap(_size,temp._size);
swap(_capacity,temp._capacity);
}
//s1=s2 (这种写法不可以自己拷贝给自己)
string& operator=(string s)
{
swap(_str, s._str);
return *this;
}
//如果要拷贝自己
/*string& opeartor=(const string &s)
{
if (this != &s)
{
string temp(s);
swap(_str, temp._str);
return *this;
}
}*/
注意:这种用法是不可以自己拷贝自己的(也没有谁这样玩)
这种用法是将临时变量和所要赋值的变量交换数据,达到拷贝的目的。
将指针指向空是必要的,不然系统将会报错。因为拷贝的指针将指向随机值,释放时将会崩溃。
可以理解为点外卖
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有