C++ 中可变范围的奇怪行为
Variable scope strange behavior in C++
我的程序调用将在发生故障时设置 errno
的方法,我像异常一样抛出 errno
并捕获它:
try
{
if (-1 == truncate("/foo/bar.txt", 0))
{
throw errno;
}
}
catch (const int errno)
{
//log
}
这里我不想讨论异常处理最佳实践话题。事实是在上面的代码中,当 catch 括号中的变量名称是 errno
时,catch
块不会命中。这个问题可以简化为:
try
{
throw 1999;
}
catch (const int errno) //renaming "errno" to "e" works!!!
{
//unreachable code here
}
我知道 errno
是一个 "special" 名称,但我认为 C++ 可以正确处理在不同范围内定义的相同变量名称。
//test.h
int my_number = 99;
//test.cpp
#include "test.h"
int main()
{
try
{
throw 1999;
}
catch(int my_number)
{
std::cout << "in catch: " << my_number << std::endl; //prints 1999
}
std::cout << my_number << std::endl; //prints 99
}
该程序是在 GNU5.4 中编译的(在 C++11 和 C++14 中都有)。谁能解释这种奇怪的行为?
errno
是一个宏。因此,您的异常处理程序包含一些很可能毫无意义的扩展标记。从标准 ([errno]):
The contents of the header are the same as the POSIX header
, except that errno shall be defined as a macro.
我的程序调用将在发生故障时设置 errno
的方法,我像异常一样抛出 errno
并捕获它:
try
{
if (-1 == truncate("/foo/bar.txt", 0))
{
throw errno;
}
}
catch (const int errno)
{
//log
}
这里我不想讨论异常处理最佳实践话题。事实是在上面的代码中,当 catch 括号中的变量名称是 errno
时,catch
块不会命中。这个问题可以简化为:
try
{
throw 1999;
}
catch (const int errno) //renaming "errno" to "e" works!!!
{
//unreachable code here
}
我知道 errno
是一个 "special" 名称,但我认为 C++ 可以正确处理在不同范围内定义的相同变量名称。
//test.h
int my_number = 99;
//test.cpp
#include "test.h"
int main()
{
try
{
throw 1999;
}
catch(int my_number)
{
std::cout << "in catch: " << my_number << std::endl; //prints 1999
}
std::cout << my_number << std::endl; //prints 99
}
该程序是在 GNU5.4 中编译的(在 C++11 和 C++14 中都有)。谁能解释这种奇怪的行为?
errno
是一个宏。因此,您的异常处理程序包含一些很可能毫无意义的扩展标记。从标准 ([errno]):
The contents of the header are the same as the POSIX header , except that errno shall be defined as a macro.