C++11里面的析构函数默认noexcept抛出异常

C++语言 码拜 9年前 (2015-10-11) 1383次浏览
struct E
{
    E(const E&)=delete;
    ~E() { throw 1; }
    //不是默认noexcept吗,为何可以抛出异常?
};
int main()
{
    return 0;
}

GCC,VC编译这个程序,都没有抱错误。这是为什么呢,既然默认就是noexcept,为什么可以throw? 本人给析构函数加上了noexcept发现还是没有抱任何错误。为什么?

解决方案:5分
谁说noexcept就不能throw的?
解决方案:5分
这是一种”君子协定”

就就好比你定义一个变量是const,你仍然是有办法去修改他的值的

解决方案:5分
noexcept 保证异常不能传递出来。

假如有异常的话,会直接导致程序终止,而不会传递到这个函数以外的任何一个异常处理程序。

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 ]

解决方案:5分

也就是说你可以抛,但是抛不出去,一抛程序就挂了。


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C++11里面的析构函数默认noexcept抛出异常
喜欢 (0)
[1034331897@qq.com]
分享 (0)