右值引用用法:需要

rvalue reference usage: needed?

本文关键字:需要 用法 引用      更新时间:2023-10-16

我有一个类

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

然后是一个 util 函数,它返回 Person 列表

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())
  )
}

问题:我需要右值引用吗?它比在这里使用简单的引用有什么区别吗?

在您的情况下:

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

这两行是完全相同的。

auto&&这里是转发参考。 它将推断为右值或左值引用,具体取决于初始化的内容。

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

因此p将是Person的左值引用。

auto&&在这里(以及许多其他地方(可以解释为"我不在乎我绑定什么,但不做任何额外的副本"。 这是for(:)循环的合理默认值。

如果范围返回值,则auto&&将成为右值引用,并且引用生存期将延长。 auto&将无法编译。

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