我从 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]
返回对向量的第一个元素的引用,它本身是临时的,但我看不出问题出在哪里。
有人可以解释
- 为什么编译器会抱怨?
- 这是一个合法的警告吗?
- 如果是,我需要改变什么?
- 如果没有,我怎样才能优雅地让它静音?