Any disadvantage of using const reference when iterating over basic types?

前端 未结 2 1841
忘了有多久
忘了有多久 2020-12-25 12:16

I find myself using C++11 more and more lately, and where I would have been using iterators in the past, I now am using range-based for loops whenever possible:

<         


        
相关标签:
2条回答
  • 2020-12-25 12:42

    6.5.4/1 says:

    for ( for-range-declaration : braced-init-list ) statement
    

    let range-init be equivalent to the braced-init-list. In each case, a range-based for statement is equivalent to

    {
        auto && __range = range-init;
        for ( auto __begin = begin-expr,
                    __end = end-expr;
                __begin != __end;
                ++__begin ) {
            for-range-declaration = *__begin;
            statement
        }
    }
    

    (further explanation follows of the meanings of all that __ gubbins).

    The standard doesn't make any guarantees whether that line const auto &e = *__begin introduces a performance overhead, of course, compared with directly using *__begin instead of e inside statement. Implementations are permitted to implement references by laboriously copying a pointer into some stack slot and then reading it back each time the reference is used, and are not required to optimize.

    But there's no reason why there should be an overhead in a sensible compiler, in the case where __begin is a container iterator (whose operator* returns a reference), and then e is passed by value in statement.

    0 讨论(0)
  • 2020-12-25 12:44

    The standard containers all return references from their iterator (note, however, that some "containers aren't really container, e.g., std::vector<bool> which returns a proxy). Other iterators might return proxies or values although this isn't strictly supported.

    Of course, the standard doesn't make any guarantees with respect to performance. Any sort of performance related feature (beyond complexity guarantees) are considered to be quality of implementation.

    That said, you might want to consider having the compiler make the choice for you as it did before:

    for (auto&& e: coll) { f(e); }
    

    The main issue here is that f() may receive a non-const reference. This can be prevented if necessary using a const version of coll.

    0 讨论(0)
提交回复
热议问题