使用 VS 2015 的编译器警告 4456

Compiler Warning 4456 using VS 2015

如果我用 Visual Studio 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;
}

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();
    }
}

请注意 valueelse 的范围内。这包括(隐式)else 块中的任何嵌套 if。您可以在 C++11 的 [stmt.select] 部分第 3 段中查找:

… A name introduced by a declaration in a condition (either introduced by the type-specifier-seq or the declarator of the condition) is in scope from its point of declaration until the end of the substatements controlled by the condition. If the name is re-declared in the outermost block of a substatement controlled by the condition, the declaration that re-declares the name is ill-formed. [ Example:

if (int x = f()) {
    int x; // ill-formed, redeclaration of x
}
else {
    int x; // ill-formed, redeclaration of x
}