基于范围的 for 循环对性能有益吗?

2021-12-11 00:00:00 performance for-loop foreach c++ c++11

在 Stack Overflow 上阅读有关 C++ 迭代器和性能的各种问题**,我开始怀疑 for(auto& elem : container) 是否被编译器扩展"为最佳版本?(有点像 auto,编译器会立即推断出正确的类型,因此永远不会变慢,有时会更快).

Reading various questions here on Stack Overflow about C++ iterators and performance**, I started wondering if for(auto& elem : container) gets "expanded" by the compiler into the best possible version? (Kind of like auto, which the compiler infers into the right type right away and is therefore never slower and sometimes faster).

** 比如你写的有没有关系

** For example, does it matter if you write

for(iterator it = container.begin(), eit = container.end(); it != eit; ++it)

for(iterator it = container.begin(); it != container.end(); ++it)

对于非失效容器?

推荐答案

标准是你的朋友,见[stmt.ranged]/1

The Standard is your friend, see [stmt.ranged]/1

对于表单的基于范围的语句

For a range-based for statement of the form

for ( for-range-declaration : expression ) statement

让 range-init 等价于括号括起来的表达式

let range-init be equivalent to the expression surrounded by parentheses

( expression )

以及基于范围的 for 形式的语句

and for a range-based for statement of the form

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

让 range-init 等同于花括号初始化列表.在每种情况下,基于范围的 for 语句等效于

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
  }
}

是的,该标准保证实现最佳形式.

So yes, the Standard guarantees that the best possible form is achieved.

对于许多容器,例如 vector,在此迭代期间修改(插入/擦除)它们是未定义的行为.

And for a number of containers, such as vector, it is undefined behavior to modify (insert/erase) them during this iteration.

相关文章