c++ - 为什么对引用的赋值使用复制赋值运算符?
问题描述
对于以下示例:
#include <iostream>
using namespace std;
class Obj {
public:
Obj& operator=(const Obj& o) {
cout << "Copy assignment operator called" << endl;
return *this;
}
};
Obj o;
int update(Obj& o) {
o = ::o;
}
int main() {
Obj o2;
update(o2);
}
我得到结果:
Copy assignment operator called
为什么在将对象分配给引用时使用复制分配?为什么引用没有更新为指向分配的对象?这是惯例问题还是背后有原因?
解决方案
Assigning to a reference assigns to the object the reference refers to, not the reference itself. Thus, your update
function is equivalent to:
o2 = ::o;
推荐阅读
- xamarin - 为什么 Xamarin 绝对布局堆叠不尊重儿童顺序
- r - 将向量中多个值的每个实例替换为特定于唯一值的值
- amazon-web-services - AWS API Gateway HTTP 请求拦截器
- widget - 十月CMS | 有没有办法使用 Builder 中的文件上传小部件来使用富文本编辑器?
- dart - Dart:获取给定语言环境的货币代码
- xml - 隐藏每个组的编辑和删除按钮 Odoo 12
- javascript - 如何在表中生成不同数量的行和列
- python - AttributeError:“RegexpReplacer”对象没有属性“replace”
- google-cloud-platform - Dataprep将具有不同列数的文件导入数据集
- loops - 如何从机器人框架测试报告中删除除特定关键字之外的所有关键字