【问题标题】:Why vector<int> variable returned by const ref doesn't work [duplicate]为什么 const ref 返回的 vector<int> 变量不起作用[重复]
【发布时间】:2014-06-14 05:27:58
【问题描述】:

这是我的功能:

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

还有,

  vector<int> x = getVInt();

返回:

在抛出一个实例后调用终止 'std::out_of_range'
what(): vector::_M_range_check


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

什么都不返回(一个大小不同于 0 但在我使用 x.at(i) 时没有值的向量)。

我在论坛中寻找,但关于临时和 const ref 的答案并不能帮助我理解这一点。

谢谢。

【问题讨论】:

  • 什么是entitiesIds
  • 搞错了,是vint。
  • 您的编译器是否应该发出not提示问题的警告? (clang 3.4:Reference to stack memory associated with local variable 'vint' returned)

标签: c++ vector constants ref


【解决方案1】:

您正在返回对本地对象的引用。那是未定义的行为。而是通过副本返回,感谢RVO (return value optimization),副本将被省略。

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

【讨论】:

  • 是的,但我使用了 const。
  • @FarorTahal,没关系。
  • 退出函数后对象消失。持有对死对象的 const 引用并不重要。
  • @FarorTahal 如果按值返回,绑定到const 引用将延长返回对象的生命周期。但你不会按价值返回。
  • @FarorTahal,只需按值返回并进行复制。这是最简单和最有效的方法。 juanchopanza 指的是临时绑定到引用(const 和非const)将延长对象的生命周期的事实。在这种特定情况下,它并没有太大变化,我认为它的价值要干净得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 2018-03-17
  • 2020-03-30
  • 2012-05-03
  • 2023-03-08
  • 2017-09-20
相关资源
最近更新 更多