在这段代码中:
const int & fun(const int &i)
{
return 2*i;
}
int main()
{
const int k=3;
cout<<fun(k)<<endl;
return 0;
}
在这种情况下,fun
的参数不是本地的(没有Temporary 对象来存储Reference 返回类型)那么为什么这个警告?
+ 如果我从 function fun 的返回类型中删除 const 它说
error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
但是在删除 2* 时(只有 i 作为返回值留下)它没有显示任何错误 -> 我能想到的是这个 2 * 是将返回值转换为 Rvalue 但返回值不是 Rvalue 本身吗?我哪里错了?
最佳答案
return 2*i;
不会将 2
乘以 i
并将结果存储到 i
中。它将 2
乘以 i
并将结果放入一个临时文件中。试图通过引用返回临时文件是不行的,因为它在该行的末尾被销毁了。生命周期延长不适用于此处。
如果你想修改 i
并返回它你需要使用 operator *=
它将修改 i
并给你一个引用你可以像这样返回
return i *= 2;
但是 fun
需要使用 int&
而不是 const int &
。
如果你想返回一个右值,那么你要做的就是按值返回,比如:
int fun(const int &i)
{
return 2*i;
}
现在您可以像这样捕捉它:
int main()
{
const int& ret = fun(3);
cout << ret << endl;
return 0;
}
关于c++ - 警告 : returning reference to temporary - strange case (Clarification for Rvalue),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45255835/