在基于范围的for循环中重新声明变量(Redeclaration of variable in range

编程入门 行业动态 更新时间:2024-10-18 20:22:00
在基于范围的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.

更多推荐

本文发布于:2023-04-28 06:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1330320.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   声明   Redeclaration   variable   range

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!