我们有以下代码
int main()
{
void f() throw(int);
f();
return 0;
}
void f() { }
GCC 和 clang 编译得很好。但是,在标准中有这样一段:
n3376 15.4/4
If any declaration of a function has an exception-specification that is not a noexcept-specification allowing all exceptions, all declarations, including the definition and any explicit specialization, of that function shall have a compatible exception-specification.
下面的例子:gcc - 错误,clang - 警告
void f() throw(int);
int main()
{
f();
return 0;
}
void f() { }
为什么这些片段有差异?谢谢。
最佳答案
std 中的 n3376 15.4/4 指定函数的所有声明和定义必须具有相同的抛出类型。这里:
void f() throw(int);
int main()
{
f();
return 0;
}
void f() { }
声明 void f() throw(int);
和定义 void f() { }
在全局范围内。所以它们是冲突的,因为声明是针对一个抛出 int 的函数,而定义是针对一个没有抛出规范的函数。
现在,当您将声明放在主作用域中时,定义不在同一个作用域中,在此作用域中定义未知,因此您可以编译。
我希望你能理解我的英语,抱歉。
关于c++ - 异常规范在声明和功能实现上不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14950397/