【发布时间】:2017-12-14 08:21:24
【问题描述】:
我的程序调用将在发生故障时设置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 是一个“特殊”名称,但我认为 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可能是一个预处理器宏。 -
@Someprogrammerdude 这样吗?
-
所以预处理器会将它替换它可能定义为的任何内容,所以你有例如
const int something_which_is_not_valid_in_a_delcaration。简而言之,从不定义您自己的变量与保留符号同名。 -
宏不关心作用域(这是它们的大问题之一)。
-
@Someprogrammerdude 那为什么会编译?