以下似乎在我尝试过的几个编译器上编译:
class A { public: virtual void foo() throw() = 0; }; class B : public A { public: virtual void foo() noexcept override { } };
似乎可以用一个更新的noexcept规范覆盖一个throw()函数.我也尝试了相反的(overpiding noexcept with throw()),它似乎工作.这是为什么?这是未定义的行为还是允许的?
请注意,代码生成受到noexcept vs 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
functionstd::unexpected()
is called ([except.unexpected]),otherwise,the function
std::terminate()
is called
([except.terminate]).