c++ - 为什么 const ref 返回的 vector<int> 变量不起作用

标签 c++ vector constants ref

<分区>

这是我的功能:

const vector<int>& getVInt(){
  vector<int> vint;
  (...)
  return vint;
}

还有,

  vector<int> x = getVInt();

返回:

terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check


const vector<int>& x = getVInt();

不返回任何内容(大小不同于 0 但在我使用 x.at(i) 时没有值的 vector )。

我在论坛中查找过,但有关 temporary 和 const ref 的答案无法帮助我理解。

谢谢。

最佳答案

您正在返回对本地对象的引用。那是未定义的行为。而是通过拷贝返回,由于RVO (return value optimization),拷贝将被删除.

std::vector<int> getVInt(){
    std::vector<int> vint;
    // …
    return vint;
}

关于c++ - 为什么 const ref 返回的 vector<int> 变量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23344955/

相关文章:

c++ - 如何从 Json 中获取值

arrays - Scala 数组与向量

c++ - 如何合并两个 vector ?

c++ - 从 GCC 原子操作构建的轻量级自旋锁?

c++ - ostringstream、.str() 和重置/清除流

C++ 类外运算符实现解析为 `namespace::operator<<` 而不是 `operator<<`

matlab - 计算两个向量之间的角度matlab

c++ - golang 中的 const 方法?

c++ - VC++ 允许为 STL 容器使用 const 类型。为什么?

objective-c - 元框架/常量文件?