[英]Returning const lvalue reference to rvalue temporary? Why does this work?
Why does this code work? 为什么此代码有效? It prints out 60
every single time. 每次打印60
张。 First of all, const thingy&
indicates that the function returns a reference to an already existing variable, not a nameless construction. 首先, const thingy&
表示该函数返回对已经存在的变量的引用,而不是无名的构造。 Secondly, shouldn't that temporary die when the function returns, thus creating a null reference? 其次,当函数返回并创建空引用时,该临时函数是否不应该死亡? I am using whatever the latest GCC version is on OSX... Can somebody please explain to me why this works? 我正在使用OSX上最新的GCC版本...有人可以向我解释为什么这有效吗?
#include <iostream>
using namespace std;
struct thingy {
double things;
double moreThings;
double evenMoreThings;
};
const thingy& getThingy() {
return {60, 60, 60};
}
int main() {
cout << getThingy().evenMoreThings << endl;
}
And if that works, then why doesn't this? 如果可行,那为什么不呢?
const thingy& getThingy() {
thingy t{60, 60, 60};
return t;
}
Neither of your two options are required to work by the C++ standards, and so it shouldn't be assumed that either will necessarily work under any particular circumstances. 按照C ++标准,您的两个选项都不是必需的 ,因此不应假定这两个选项在任何特定情况下都一定有效。
Compiler specifics have caused the first option to work where you return the value directly. 编译器的特殊性导致第一个选项在您直接返回值的地方起作用。
Ideally, you would return by value ( thingy getThingy();
) instead to ensure compatibility. 理想情况下,您thingy getThingy();
值返回( thingy getThingy();
)以确保兼容性。 Any compiler worth your time will still apply return value optimisation to this, preventing the need for a copy constructor call and still allowing the necessary efficiency. 任何值得您花费时间的编译器仍将对此应用返回值优化,从而避免了对复制构造函数的调用,并且仍然允许必要的效率。
The compiler is performing the Return Value Optimization here. 编译器在这里执行返回值优化。
https://en.wikipedia.org/wiki/Return_value_optimization https://zh.wikipedia.org/wiki/返回值优化
The compiler is able to take the value constructed at the return and won't even need to copy it. 编译器能够采用返回值构造的值,甚至不需要复制它。 However, in the example where you construct the struct inside the function, it really is a local variable, and thus falls out of scope at the end of the function, invalidating the reference. 但是,在您在函数内部构造struct的示例中,它实际上是一个局部变量,因此在函数末尾超出范围,使引用无效。
We should not mix rvalue and lvalue references. 我们不应该混合使用rvalue和lvalue引用。 The best option is to return by copy.. 最好的选择是通过复印返回。
Returning lavalue rerense of local variable will always lead to problems. 返回局部变量的lavalue rerense总是会导致问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.