【问题标题】:rvalue reference usage: needed?右值参考用法:需要吗?
【发布时间】:2019-05-28 17:57:29
【问题描述】:

我有课

class Person {
  // some other fields for this object
  std::vector<string> relatives;
}

然后是一个返回人员列表的 util 函数

std::vector<Person> getSomePerson() {
  // implementation details...
}

现在我要循环遍历:

for (auto&& p: getSomePerson()) {  <---- do I need the rvalue reference???
  // use p
  some_other_vector.insert(
      std::make_move_iterator(p.relatives.begin()),
      std::make_move_iterator(p.relatives.end())
  )
}

问题:我需要右值引用吗?与在这里使用简单的参考有什么不同吗?

【问题讨论】:

  • Duplicate?您似乎在暗示使用错误识别的右值引用与 getSoemPerson() 是右值有关。不是。
  • 信息太少,无法正确回答。根据提供的信息,我不知道您是否需要右值 ref。
  • 已更新,我需要使用右值引用还是简单的引用可以工作?我想它无论如何都会复制?

标签: c++ c++14 rvalue-reference rvalue


【解决方案1】:

在你的情况下:

for (auto&& p: getSomePerson()) {
for (auto& p: getSomePerson()) {  

这两行完全相同。

auto&amp;&amp; 这里是转发参考。它将根据初始化的内容推断为右值或左值引用。

被迭代的范围是向量类型的右值。它的迭代器 operator* 返回一个左值引用。

所以p 将是对Person 的左值引用。

auto&amp;&amp; 可以在这里(和许多其他地方)解释为“我不在乎我绑定到什么,但不要制作任何额外的副本”。这是for(:) 循环的合理默认值。

如果您的范围返回值,auto&amp;&amp; 将成为右值引用,并且会发生引用生命周期延长。 auto&amp; 将无法编译。

auto const&amp; 是另一个合理的选择;它很像auto&amp;&amp;,但你也保证不会修改你所指的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-06
    • 1970-01-01
    相关资源
    最近更新 更多