如果我使用Visual 2015编译以下小程序,则在第9行中会得到以下编译器警告:
warning C4456: Declaration of "iter" shadows previous declaration这是我的小节目:
#include <iostream>
#include <boost/variant.hpp>
int main(int argc, char** args) {
boost::variant<double, int> v{ 3.2 };
if (auto iter = boost::get<int>(&v)) {
std::cout << *iter << std::endl;
}
else if( auto iter = boost::get<double>(&v)) {
std::cout << *iter << std::endl;
}
}我很好奇这是编译器的错误还是严重的错误。
修订的
正如@Zeta所发现的,以下是合法的C++代码,甚至我从未想过。由于使用未定义的iter,该程序将崩溃。
#include <iostream>
#include <boost/variant.hpp>
int main(int, char**) {
boost::variant<double, int> v{ 3.2 };
if (auto iter = boost::get<int>(&v)) {
std::cout << *iter << std::endl;
}
else if( auto iter2 = boost::get<double>(&v)) {
std::cout << *iter2 << std::endl;
std::cout << *iter << std::endl;
}
return 0;
}发布于 2018-03-12 10:45:00
VS是正确的。您手头有两个iter:
#include <iostream>
#include <boost/variant.hpp>
int main(int argc, char** args) {
boost::variant<double, int> v{ 3.2 };
if (auto iter = boost::get<int>(&v)) {
std::cout << *iter << std::endl;
}
else if( auto iter2 = boost::get<double>(&v)) {
std::cout << *iter << std::endl; // whoops
}
}那是因为
if(value = foo()) {
bar();
} else {
quux();
}是相同的
{
value = foo();
if(value) {
bar();
} else {
quux();
}
}注意,value是else的作用域。这包括(隐式) if块中的任何嵌套else。您可以在C++11的stmt.select部分,第3段中查看此内容:
…由条件中的声明引入的名称(由类型说明符-seq或条件的声明者引入)从声明点一直到条件控制的子语句结束。如果名称在由条件控制的子语句的最外层块中重新声明,则重新声明名称的声明是格式错误的。[例子: 如果(int x= f()) { int x;//,则重新声明x}ill{ int x;// redeclaration,重新声明x}
https://stackoverflow.com/questions/49230548
复制相似问题