强制 auto 成为循环范围内的引用类型 [英] Forcing auto to be a reference type in a range for loop
问题描述
假设我有 foo
,它是一个填充的 std::vector
.
Suppose I have foo
which is a populated std::vector<double>
.
我需要对这个向量的元素进行操作.我有动力写
I need to operate on the elements of this vector. I'm motivated to write
for (auto it : foo){
/*ToDo - Operate on 'it'*/
}
但看起来这不会写回 foo
,因为 it
是一个值类型:向量元素的深层副本已被获取.
But it appears that this will not write back to foo
since it
is a value type: a deep copy of the vector element has been taken.
我可以为 auto
提供一些指导以使 it
成为引用类型吗?然后我就可以直接对it
进行操作了.
Can I give some guidance to auto
to make it
a reference type? Then I could operate directly on it
.
我怀疑我遗漏了一些琐碎的语法.
I suspect I'm missing some trivial syntax.
推荐答案
最小的 auto
参考
A minimal auto
reference
循环可以声明如下:
for (auto& it : foo) {
// ^ the additional & is needed
/*ToDo - Operate on 'it'*/
}
这将允许 it
成为对 foo
中每个元素的引用.
This will allow it
to be a reference to each element in foo
.
对于这些循环的规范形式"存在一些争论,但在这种情况下 auto&
应该可以解决问题.
There is some debate as to the "canonical form" of these loops, but the auto&
should do the trick in this case.
一般auto
参考
General auto
reference
在更一般的意义上(在容器的细节之外),以下循环有效(并且可能更可取).
In a more general sense (outside the specifics of the container), the following loop works (and may well be preferable).
for (auto&& it : container) {
// ^ && used here
}
auto&&
允许绑定到左值和右值.当在通用或一般(例如模板情况)中使用时,此表单可能会达到所需的平衡(即引用、副本、prvalue/xvalue 返回(例如代理对象)等).
The auto&&
allows for bindings to lvalues and rvalues. When used in a generic or general (e.g. template situation) this form may strike the desired balance (i.e. references, copies, prvalue/xvalue returns (e.g. proxy objects) etc.).
倾向于使用一般的 auto&&
,但如果您必须对表单进行具体说明,则使用更具体的变体(例如 auto
、autoconst&
等).
Favour the general auto&&
, but if you have to be specific about the form, then use a more specific variation (e.g. auto
, auto const&
etc.).
为什么 auto&&
更好?
Why is auto&&
better?
如此处的其他答案和评论中所述.为什么 auto&&
更好?在大多数情况下,它会做你认为应该做的事情,参见 本提案 和 更新.
As noted in other answers here and the comments. Why is auto&&
better? Simply it will do what you think it should in most cases, see this proposal and its update.
一如既往,Scott Meyers 的 博客 也适合阅读此内容.
As always, Scott Meyers' blog about this also makes for a good read.
这篇关于强制 auto 成为循环范围内的引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!