2

我从 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]返回对向量的第一个元素的引用,它本身是临时的,但我看不出问题出在哪里。

有人可以解释

  • 为什么编译器会抱怨?
  • 这是一个合法的警告吗?
    • 如果是,我需要改变什么?
    • 如果没有,我怎样才能优雅地让它静音?
4

3 回答 3

4

不,这不合法。的返回值g()是临时的,但它不是 const - 您只是无法获得对它的非常量引用。非常量成员operator[]在此处调用是完全有效的,双精度到整数的转换同样安全。

于 2011-04-19T12:09:45.933 回答
2

这个 Sun 编译器看起来很奇怪,对我来说根本不合法。Ideone编译它没有问题。

关于静音部分:

std::vector<double> const tmp = g();
int b = tmp[0];

也就是说,引入一个命名变量而不是让临时浮动。

编辑:

正如评论中所建议的,对返回值进行 const 限定可能会有所帮助。

std::vector<double> const g();

int main() {
  int b = g()[0];
  return b;
}
于 2011-04-19T12:15:28.277 回答
1

是的,它确实使用临时初始化了非常量引用。但仅在概念上在重载解决期间而不是实际上。编译器不应对此发出警告。

在重载决议中,operator[]有这个函数参数签名

operator[](std::vector<int>&, std::vector<int>::size_type);

第一个参数将接收由g().

于 2011-04-19T18:46:51.873 回答