c++ - C++ 标准对使用 noexcept 覆盖 throw() 函数有何规定?

标签 c++ c++11

以下似乎可以在我试过的几个编译器上编译:

class A
{
public:
    virtual void foo() throw() = 0;
};

class B : public A
{
public:
    virtual void foo() noexcept override { }
};

似乎可以用较新的 noexcept 规范覆盖 throw() 函数。我也尝试了相反的方法(用 throw() 覆盖 noexcept),它似乎有效。这是为什么?这是未定义的行为还是允许的?

请注意,代码生成受 noexcept 与 throw() 的影响。它们也没有等效的行为,因为 noexcept 调用的终止函数与 throw() 不同。一个理想的答案是指出行为差异以及它们在这种情况下重要或不重要的原因。

最佳答案

您甚至可以在不覆盖的情况下执行此操作:

void f() throw();
void f() noexcept { throw 1; }

[except.spec]/9明确表示控制发生的事情的是定义的规范:

Whenever an exception of type E is thrown and the search for a handler ([except.handle]) encounters the outermost block of a function with an exception specification that does not allow E, then,

  • if the function definition has a dynamic-exception-specification, the function std::unexpected() is called ([except.unexpected]),

  • otherwise, the function std::terminate() is called ([except.terminate]).

这不是问题,因为对此的任何特殊处理都发生在被调用方,而不是调用方;调用者只需要知道没有异常会离开该函数。

关于c++ - C++ 标准对使用 noexcept 覆盖 throw() 函数有何规定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40226269/

相关文章:

c++ - 不了解如何为源/接收器类逻辑初始化指针

c++ - 元组 View 的元素类型

c++ - constexpr 用于派生类中空初始化的构造函数

c++ - 函数返回的 decltype

c++ - 在 C++ 类中注册 python 可调用对象

c++ - 如何使用 C++ 执行 gvim 命令

c++ - 异构序列发生器

c++ - 使用可变参数模板限制模板类的受支持类型

c++ - 如何单击 wxWidgets 处理程序 OnClose 中的按钮?

c++ - 如何使用 SHGetKnownFolderPath API 中的 CString 对象获取程序数据路径