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

Mot*_*oth 1 c++ const vector ref

这是我的功能:

const vector<int>& getVInt(){
  vector<int> vint;
  (...)
  return vint;
}
Run Code Online (Sandbox Code Playgroud)

和,

  vector<int> x = getVInt();
Run Code Online (Sandbox Code Playgroud)

收益:

在抛出'std :: out_of_range'的实例后调用终止
what():vector :: _ M_range_check


const vector<int>& x = getVInt();
Run Code Online (Sandbox Code Playgroud)

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

我在论坛中寻找,但关于temprorary和const ref的答案并没有帮助我理解这一点.

谢谢.

Sho*_*hoe 7

您将返回对本地对象的引用.这是未定义的行为.相反,通过复制返回,由于RVO(返回值优化),副本将被删除.

std::vector<int> getVInt(){
    std::vector<int> vint;
    // …
    return vint;
}
Run Code Online (Sandbox Code Playgroud)

  • @FarorTahal如果按值返回,绑定到`const`引用将延长返回对象的生命周期.但是你没有按价值回报. (3认同)
  • 退出该函数后,该对象消失了.你持有对死对象的const引用并不重要. (2认同)