以下似乎可以在我试过的几个编译器上编译:
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/