我们有一堆值返回函数:
Foo function_1(){
Foo f;
// ...
return f;
}
Bar function_2(){
Bar b;
// ...
return b;
}
Baz function_3(){
Baz b;
// ...
return b;
}
我正在使用它们来创建局部变量的实例化:
void example(){
//...
const auto foo = function_1();
//...
const auto bar = function_2();
//...
const auto baz = function_3();
}
但是,我的队友一直要求我将所有实例化转换为使用 &
:
void example(){
//...
const auto& foo = function_1();
//...
const auto& bar = function_2();
//...
const auto& baz = function_3();
}
这样做的理由似乎符合以下问题:
Why not always assign return values to const reference?
我知道 auto& x =
和 auto x =
要求的是两种不同的东西,并且行为可能因函数的实现而异。
话虽这么说,我正在寻找有关选择在值返回函数上执行此操作时的差异(如果有的话)的说明?行为是否保证相同?
如果它是一个值返回函数,我如何在 const auto&
和 const auto
之间做出选择? (大概 const 在这里无关紧要?)。我在 C++ Core Guidelines 中找不到关于此的任何建议。我希望这不是一个自以为是的问题。
最佳答案
您的同事正在尝试执行编译器的工作而不是信任它,结果可能是悲观的。 NRVO 得到很好的支持,如果函数是用值语义编写的,NRVO 可以省略多个拷贝。绑定(bind)到引用将阻止这种情况,因为引用变量将不满足此优化的条件。 A simple test to demonstrate :
#include <iostream>
struct Test {
Test() { std::cout << "Created\n"; }
Test(const Test&) { std::cout << "Copied\n"; }
};
Test foo() {
Test t;
return t;
}
Test bar_good() {
const auto t = foo();
return t;
}
Test bar_bad() {
const auto& t = foo();
return t;
}
int main() {
const auto good = bar_good(); (void)good;
std::cout << "===========\n";
const auto& bad = bar_bad(); (void)bad;
}
给出输出:
Created
===========
Created
Copied
当使用值语义时一个对象总计,但当使用引用时是一个冗余拷贝。根据拷贝(甚至 move )的扩展程度,您可能会看到明显的性能差异。
关于c++ - 我应该将 ref 还是拷贝分配给值返回函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50106884/