在基于范围的 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/