Forcing auto to be a reference type in a range for loop

后端 未结 4 1085
春和景丽
春和景丽 2020-12-17 09:29

Suppose I have foo which is a populated std::vector.

I need to operate on the elements of this vector. I\'m motivated to writ

4条回答
  •  暖寄归人
    2020-12-17 09:57

    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.

提交回复
热议问题