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/

相关文章:

javascript - knockout 映射和 foreach 数据绑定(bind)在带有按钮的表上,缺少对 View 模型的引用?

bash - 命令返回数据到变量的返回状态

c++ - CC1不能在类定义中初始化,为什么?那我将如何初始化它?请有人帮助我

c++ - 如何限制Qt中的日志大小

c++ - 确保dynamic_cast不会导致未定义的行为C++

r - R 中出现 "Variable Lengths Differ"错误的原因是什么?

c++ - strncmp 没有正确匹配

c++ - 具有引用成员的赋值运算符

go - 命名从多返回函数接收变量

c++ - 将问题模板与返回联系起来