What is clang's 'range-loop-analysis' diagnostic about?

℡╲_俬逩灬. 提交于 2019-12-04 07:33:41

In C++17 a range based for loop is defined as

{
    auto && __range = range_expression ; 
    auto __begin = begin_expr ;
    auto __end = end_expr ;
    for ( ; __begin != __end; ++__begin) { 
        range_declaration = *__begin; 
        loop_statement 
    } 
}

And

range_declaration = *__begin;

Is the point where the range variable is initialized. Typically *__begin returns a reference so in

for (const auto& e : range_that_returns_references)

e can be eliminated and we can just work with the element from the range. In

for (const auto& e : range_that_returns_proxies_or_copies)

e can't be eleminated. *__begin will create a proxy or copy and then we bind that temporary to e. That means in every iteration you have an object that is being crated and destroyed ,which could be costly, and is not obvious as you are using a reference. The warning wants you to use a non reference type to make it obvious that you are not actually working with the element from the range but instead a copy/proxy of it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!