c++ - 异常规范在声明和功能实现上不兼容

标签 c++ c++11 g++ clang++

我们有以下代码

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/

相关文章:

c++ - 使用调试选项时 dwarfdump 为空

c++ - 为什么不重载 std::vector::erase 以获取整数索引?

c++ - 未在此范围内声明“num1”

c++ - 如何在 C++ 中执行命令并获取命令的返回码 stdout 和 stderr

c++ - 如何在main之前强制初始化静态局部变量?

c - If 语句检查 argv 是否为数字

c++ - QGL小部件: overpainting with QPainter

c++ - 正确使用reinterpret_cast的方法

c++ - 如何创建不区分大小写的正则表达式来匹配文件扩展名?

compilation - CMake:连续两次编译程序