C ++ 11基于范围的循环:按值或引用获取项 [英] C++11 range based loop: get item by value or reference to const

查看:150
本文介绍了C ++ 11基于范围的循环:按值或引用获取项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读基于范围的循环的一些示例,他们建议两种主要方式 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆