C ++ 11基于范围的循环:按值或引用获取项 [英] C++11 range based loop: get item by value or reference to const
问题描述
阅读基于范围的循环的一些示例,他们建议两种主要方式 1 , 2 ,3 , 4
std :: vector< MyClass> vec;
for(auto& x:vec)
{
// x是对vec项的引用
//我们可以通过更改x
}
或
for(auto x:vec)
{
// x的值从vec的项目复制
//我们不能更改vec的项目通过更改x
}
好了。
当我们不需要更改 vec
项目时,IMO建议使用第二个版本(按值)。为什么他们不建议 const
引用(至少我没有找到任何直接的建议):
for(auto const& x:vec)//< - 参见const关键字
{
// x是对vec的const项的引用
//我们不能通过改变x
来改变vec的项目
Isn' t更好?它不会在每次迭代中避免多余的副本,而它是 const
?
如果您不想更改项目以及想要避免制作副本,则 auto const&
正确的选择:
for(auto const& x:vec)
pre>
谁建议你使用
auto&
是错误的。
- 选择
- 当您想要使用副本时,请选择
auto x
- 如果您想使用原始项目,请选择
auto const& x
不修改它们。
- 当您想要使用副本时,请选择
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
}
or
for (auto x : vec)
{
// Value of x is copied from an item of vec
// We can not change vec's items by changing x
}
Well.
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
}
Isn't it better? Doesn't it avoid a redundant copy in each iteration while it's a 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)
Whoever suggests you to use auto &
is wrong. Ignore them.
Here is recap:
- Choose
auto x
when you want to work with copies. - Choose
auto &x
when you want to work with original items and may modify them. - Choose
auto const &x
when you want to work with original items and will not modify them.
这篇关于C ++ 11基于范围的循环:按值或引用获取项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!