c++ - 为什么当我尝试返回引用时我的对象仍然被复制
问题描述
class Obj {
public:
Obj(int aa, int bb): a(aa), b(bb) {}
Obj(const Obj& o) {a = o.a; b = o.b;std::cout << "copying" << std::endl;}
Obj(Obj&& o) {a = o.a; b = o.b;std::cout << "moving" << std::endl;}
int a;
int b;
};
const Obj& Min(const Obj &o1, const Obj &o2) {
if (o1.a > o2.a) {
return o1;
} else {
return o2;
}
}
int main() {
using namespace std;
auto o1 = Obj(1,1);
auto o2 = Obj(2,2);
auto res = Min(o1, o2);
cout << res.a << endl;
res.a = 100;
cout << o1.a << endl;
cout << o2.a << endl;
return 0;
}
程序仍然打印一个字copying
,表示复制构造函数已激活。那么构造函数在哪里调用呢?为什么函数不返回对的引用,o1
从而修改 的值res
也会改变 的值o1
?
解决方案
副本在语句中完成:
auto res = Min(o1, o2);
Min()
返回类型是const Obj&
. 以上auto
将推导出为Obj
,而不是const Obj&
(即,res
类型将是Obj
)。res
是一个对象,通过复制构造函数(即Obj::Obj(const Obj&)
)进行初始化,因此发生了复制构造。
如果你改为写:
auto& res = Min(o1, o2)
res
将是类型const Obj&
,并且不会在那里进行复制构造,因为res
将是引用,而不是对象。
推荐阅读
- mysql - MySQL 在多重连接语句中更新,只有第三个表中的最高值
- javascript - 如何在 React 中同步测试?
- python - AWS Lambda - 将 S3 中的多个 CSV 文件合并到一个文件中
- asp.net-mvc - 处理请求时发生未处理的异常。当我想按类别列出产品时出现此错误?
- javascript - 将新元素添加到对象数组并在 HTML 中显示
- algorithm - 在python中有效地查找最近的坐标(Long,Lat)
- r - 使用正则表达式将字符串中的数字替换为四舍五入的数字
- reactjs - “在‘redux’中找不到导出‘createStore’
- terraform - 将多个不同大小的 EBS 卷附加到 EC2 实例
- java - 创建一个扩展 java.io.PrintStream 类的类