struct E { E(const E&)=delete; ~E() { throw 1; } //不是默认noexcept吗,为何可以抛出异常? }; int main() { return 0; }
GCC,VC编译这个程序,都没有抱错误。这是为什么呢,既然默认就是noexcept,为什么可以throw? 本人给析构函数加上了noexcept发现还是没有抱任何错误。为什么?
就就好比你定义一个变量是const,你仍然是有办法去修改他的值的
假如有异常的话,会直接导致程序终止,而不会传递到这个函数以外的任何一个异常处理程序。
ISO/IEC 14882:2011
15.4 Exception specifications
9 Whenever an exception is thrown and the search for a handler (15.3) encounters the outermost block of a
function with an exception-specification that does not allow the exception, then,
— if the exception-specification is a dynamic-exception-specification, the function std::unexpected() is
called (15.5.2),
— otherwise, the function std::terminate() is called (15.5.1).
[ Example:
class X { }; class Y { }; class Z: public X { }; class W { }; void f() throw (X, Y) { int n = 0; if (n) throw X(); // OK if (n) throw Z(); // also OK throw W(); // will call std::unexpected() }
— end example ]
[ Note: A function can have multiple declarations with different non-throwing exception-specifications; for
this purpose, the one on the function definition is used. — end note ]
也就是说你可以抛,但是抛不出去,一抛程序就挂了。