C++ iterators & loop optimization

前端 未结 11 1162
渐次进展
渐次进展 2021-01-30 04:11

I see a lot of c++ code that looks like this:

for( const_iterator it = list.begin(),
     const_iterator ite = list.end();
     it != ite; ++it)
<
11条回答
  •  被撕碎了的回忆
    2021-01-30 04:35

    Consider this example:

    for (const_iterator it = list.begin(); it != list.end(); ++list)
    {
        if (moonFull())
            it = insert_stuff(list);
        else
            it = erase_stuff(list);
    }
    

    in this case, you NEED to call list.end() in the loop, and the compiler isn't going to optimize that away.

    Other cases where the compiler can prove that end() is always returning the same value, optimization can take place.

    If we are talking about STL containers, than i think any good compiler can optimize away multiple end() calls when multiple end() calls is not needed for the programming logic. However, if you have a custom container and implementation of end() is not in the same translation unit, than optimization will have to happen at link time. I know very little about link time optimization, but i'll bet most linkers will not do such optimization.

提交回复
热议问题