基于范围的循环:按值获取项目还是对 const 的引用?

2021-12-12 00:00:00 c++ c++11

阅读一些基于范围的循环示例,他们提出了两种主要方法 1,2、3, 4

Reading some examples of range based loops they suggest two main ways 1, 2, 3, 4

std::vector<MyClass> vec;

for (auto &x : vec)
{
  // x is a reference to an item of vec
  // We can change vec's items by changing x 
}

for (auto x : vec)
{
  // Value of x is copied from an item of vec
  // We can not change vec's items by changing x
}

嗯.

当我们不需要更改 vec 项时,IMO、Examples 建议使用第二个版本(按值).为什么他们不建议 const 引用的东西(至少我没有找到任何直接的建议):

When we don't need changing vec items, IMO, Examples suggest to use second version (by value). Why they don't suggest something which const references (At least I have not found any direct suggestion):

for (auto const &x : vec) // <-- see const keyword
{
  // x is a reference to an const item of vec
  // We can not change vec's items by changing x 
}

不是更好吗?当它是一个const 时,它不是避免了每次迭代中的冗余副本吗?

Isn't it better? Doesn't it avoid a redundant copy in each iteration while it's a const?

推荐答案

如果你不想改变项目又想避免复制,那么 auto const & 是正确的选择:

If you don't want to change the items as well as want to avoid making copies, then auto const & is the correct choice:

for (auto const &x : vec)

建议您使用 auto & 的人是错误的.忽略它们.

Whoever suggests you to use auto & is wrong. Ignore them.

这里是回顾:

  • 如果要处理副本,请选择 auto x.
  • 如果您想使用原始项目并可能对其进行修改,请选择 auto &x.
  • 如果您想使用原始项目而不修改它们,请选择 auto const &x.

相关文章