gpt4 book ai didi

c++ - 警告 : should not initialize a non-const reference with a temporary

转载 作者:搜寻专家 更新时间:2023-10-31 00:03:37 25 4
gpt4 key购买 nike

我从 Sun Studio 12.1 的标题中收到警告,代码片段如下:

#include <vector>

std::vector<int> g()
{
std::vector<int> result;
result.push_back(5);
return result;
}

int main()
{
int b = g()[0]; // <- Warning in this line

return b;
}

警告文本是:

Warning: should not initialize a non-const reference with a temporary.

虽然我知道用临时变量初始化非常量引用是一件坏事,但我看不出这是怎么发生的。我知道 [0] 返回对 vector 第一个元素的引用,它本身是临时的,但我看不出问题出在哪里。

谁能解释一下

  • 为什么编译器会报错?
  • 这是一个合理的警告吗?
    • 如果是,我需要更改什么?
    • 如果不是,我怎样才能优雅地使其静音?

最佳答案

不,这是不合法的。 g() 的返回值是一个临时值,但它不是 const - 你只是不能得到一个非 const 引用它。非常量成员 operator[] 在这里调用是完全有效的, double 到整数的转换同样安全。

关于c++ - 警告 : should not initialize a non-const reference with a temporary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5716064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com