c++ - 在复制赋值运算符中按值传递与按引用传递
问题描述
首先,有一个类似的热门帖子What is the copy-and-swap idiom?. 接受的答案具有指向https://web.archive.org/web/20140113221447/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/的链接。
接受和链接的页面都表明复制赋值运算符的常用实现是(从上一个链接复制和粘贴)
T& T::operator=(T const& x) // x is a reference to the source
{
T tmp(x); // copy construction of tmp does the hard work
swap(*this, tmp); // trade our resources for tmp's
return *this; // our (old) resources get destroyed with tmp
}
但那
T& operator=(T x) // x is a copy of the source; hard work already done
{
swap(*this, x); // trade our resources for x's
return *this; // our (old) resources get destroyed with x
}
由于编译器的复制省略优化,更好,或者通常,总是按值传递而不是通过引用传递,然后复制通过引用传递的参数。
我同意第二个选项与第一个选项相同或更好,但并不差,但我很困惑为什么第一个选项一开始就是这样写的。我不明白为什么需要临时变量和交换。
相反,我们不能只做类似的事情:
T& T::operator=(T const& x) // x is a reference to the source
{
this->member_var = x.member_var;
//if we have to do a deep copy of something, implement that here
return *this;
}
它不使用复制构造函数。
解决方案
如果有多个成员,您的赋值运算符不是异常安全的:
T& T::operator=(T const& x)
{
this->member_var1 = x.member_var1;
this->member_var2 = x.member_var2; // if an exception occurs here, this->member_var1 will still be changed
return *this;
}
推荐阅读
- git - 如何撤消两次提交之间的更改?
- kubernetes - 如何忽略部署文件中的随机 kubernetes pod 名称
- excel - 在正确的位置插入图片
- mql4 - 使用 mql4 交替买卖订单
- aspectj - 如何为内联生成的类初始化创建切入点(龙目岛记录器)
- r - 通过R中的OCR从pdf读取文本
- flutter - GestureDetector 在 TabBarView 上不起作用
- ssl - 仅在本地计算机上:[SSL: CERTIFICATE_VERIFY_FAILED] _ssl.c:1108) 错误
- c - 控制流结构中没有指定返回语句的函数返回值
- angular6 - 每次 ngFor 迭代都有不同的组件视图