c++ - 在基于范围的表达式和声明中具有相同名称的标识符

标签 c++ for-loop c++11 scope

在基于范围的 for 循环中声明一个与我在循环的表达式语句中使用的名称相同的循环变量是否合法?我希望这个例子能说明问题。

#include <iostream>
#include <vector>

struct bar {
    std::vector<int> nums;
};

int main()
{
    bar b;
    b.nums = {1, 2, 3};

    for(int b : b.nums)
        std::cout << b << std::endl;   
}

gcc 4.8 给出一个错误,而 clang 3.2 允许它。

最佳答案

根据我对 C++2011 6.5.4 的阅读,您的代码:

bar b;

for(int b : b.nums)
    std::cout << b << std::endl;

应转换为:

bar b;

{
   auto && __range = b.nums;
   for (auto __begin = __range.begin(), __end = __range.end(); __begin != __end; ++__begin ) {
       int b = *__begin;
       std::cout << b << std::endl;
   }
}

这对我来说意味着 clang 是正确的。

关于c++ - 在基于范围的表达式和声明中具有相同名称的标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16407212/

相关文章:

java - 如何连接到 802.15.4 帧流?

c++ - 抽象工厂构建失败的最佳实践

c++ - 如何让 std::thread 停止?

c - 旋转存储像素的矩阵

c++ - MoveInsertable 和 CopyInsertable 之间的区别?

C++ 运算符= return *this 后的结果发生变化

c++ - Cmake 错误 : The following variables are used in the project, 但它们被设置为 NOTFOUND 试图在 archlinux 中编译 Rigs of Rods

c++ - qmake配置的含义是什么

ios - 如何从NSMutableArray设置实例变量?

c - 如何在 while 循环中的嵌套 for 循环上使用 OpenMP?