A minimal auto
reference
The loop can be declared as follows:
for (auto& it : foo) {
// ^ the additional & is needed
/*ToDo - Operate on 'it'*/
}
This will allow it
to be a reference to each element in foo
.
There is some debate as to the "canonical form" of these loops, but the auto&
should do the trick in this case.
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
}
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.).
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.).
Why is auto&&
better?
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.
As always, Scott Meyers' blog about this also makes for a good read.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…