c++ - 警告 : returning reference to temporary - strange case (Clarification for Rvalue)

标签 c++ reference return-value rvalue temporary

在这段代码中:

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/

相关文章:

c++ - 将指针与引用进行比较

c++ - 对于级联成员函数调用,为什么需要返回引用?为什么只有 this 指针还不够?

在c中调用一个函数以在另一个函数调用中返回一个字符串

function - 如何将任意数据类型写入Matlab元胞数组

c++ - opencv 的 Sysmalloc 错误

c++ - 创建对象时调用的构造函数

.net - CLSCompliant(true) 拖入未使用的引用

android - 从 Kotlin (Android) 中的监听器 onSuccess() 返回一个值

c++ - 移除未使用的模板实例化的静态成员

c++ - 遍历所有可能的位排列