gpt4 book ai didi

c++ - 使用 VS 2015 的编译器警告 4456

转载 作者:行者123 更新时间:2023-11-28 01:35:58 25 4
gpt4 key购买 nike

如果我用 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 block 中的任何嵌套 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
}

关于c++ - 使用 VS 2015 的编译器警告 4456,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49230548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com