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

后端 未结 4 1083
春和景丽
春和景丽 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 10:00

    I would use auto&&:

    for (auto&& it : foo) {
        // bla
    }
    

    The reason is spelt out in N3994 "Range-Based For-Loops: The Next Generation (Revision 1)" that it would better work with proxy objects (such as those coming from std::vector).

    In fact, that proposal for C++1z (supported already by Clang 3.5 SVN in -std=c++1z mode) proposes the syntax:

    // c++1z only
    for (it : foo) { 
        // bla
    }
    

    as a short-hand for for (auto&& it : foo).

    Update: the N3994 proposal was not voted into the C++17 working paper.

提交回复
热议问题