简体   繁体   English

在基于范围的for循环中重新声明变量

[英]Redeclaration of variable in range-based for loops

This code fails with GCC 4.8.1 but works with MSVC2013: 此代码在GCC 4.8.1中失败,但与MSVC2013一起使用:

#include <vector>
#include <string>

int main()
{
  std::vector<int> V{1,2,3,4,5};

  for (auto i : V)
  {
    std::string i = "oups";
  }
}

GCC 4.8.1 tells: GCC 4.8.1告诉:

prog.cpp:10:17: error: redeclaration of ‘std::string i’
     std::string i = "oups";
                 ^

Is it some bug in the MSVC 2013 compiler? 它是MSVC 2013编译器中的一些错误吗?

Yes, it's a bug, but in GCC. 是的,这是一个错误,但在海湾合作委员会。 C++11[stmt.ranged] clearly states that your range-based for loop is equivalent to this: C ++ 11 [stmt.ranged]明确指出基于范围的for循环等效于:

{
  auto && __range = (V);
  for ( auto __begin = __range.begin(),
             __end = __range.end();
        __begin != __end;
        ++__begin ) {
    auto i = *__begin;
    {
      std::string i = "oups";
    }
  }
}

So the inner i should simply hide the loop-control i without any problems. 所以内部i应该简单地隐藏循环控制i没有任何问题。

And, as this live example shows, when spelled out like this, GCC actually accepts it just fine. 而且,正如这个实例所示,当这样拼写时,GCC实际上接受它就好了。

Its a bug in GCC, as well as Clang 这是GCC中的一个错误,还有Clang

See Range Based For-loop 请参阅基于范围的For循环

for ( range_declaration : range_expression ){ loop_statement }

will be equivalent to 将等同于

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

On another note, on Visual C++ 2013 另一方面,在Visual C ++ 2013上

for (auto i : V) std::string i = "oups"; 
       /* match this with equivalent for-loop
          loop-statement aren't in braces
      */

shouldn't compile. 不应该编译。

c++11 [stmt.ranged] tells that the range-for loop expands into this : c ++ 11 [stmt.ranged]告诉range-for循环扩展为:

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

Contrary to other answers, I am claiming there are no scopes for the statements, and that this is a MSVC's bug (not gcc or clang). 与其他答案相反,我声称声明没有范围,这是MSVC的错误(不是gcc或clang)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM