Range based loop: get item by value or reference to const?(基于范围的循环:按值获取项目还是对 const 的引用?)
问题描述
阅读一些基于范围的循环示例,他们提出了两种主要方法 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
.
这篇关于基于范围的循环:按值获取项目还是对 const 的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:基于范围的循环:按值获取项目还是对 const 的引用


基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30