在基于范围的for循环中重新声明变量(Redeclaration of variable in range-based for loops)
此代码在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告诉:
prog.cpp:10:17: error: redeclaration of ‘std::string i’ std::string i = "oups"; ^它是MSVC 2013编译器中的一些错误吗?
This code fails with GCC 4.8.1 but works with 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:
prog.cpp:10:17: error: redeclaration of ‘std::string i’ std::string i = "oups"; ^Is it some bug in the MSVC 2013 compiler?
最满意答案
是的,这是一个错误,但在海湾合作委员会。 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"; } } }所以内部i应该简单地隐藏循环控制i没有任何问题。
并且,正如这个实例所示,当这样拼写时,GCC实际上接受它就好了。
Yes, it's a bug, but in GCC. C++11[stmt.ranged] clearly states that your range-based for loop is equivalent to this:
{ 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.
And, as this live example shows, when spelled out like this, GCC actually accepts it just fine.
更多推荐
发布评论