专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > C++

C++11里面的析构函数默认是noexcept对吧? 为什么还可以抛出错误

发布时间:2011-06-28 10:25:01 文章来源:www.iduyao.cn 采编人员:星星草
C++11里面的析构函数默认是noexcept对吧? 为什么还可以抛出异常?

struct E
{
    E(const E&)=delete;
    ~E() { throw 1; }
    //不是默认noexcept吗,为何可以抛出异常?
};
int main()
{
    return 0;
}

GCC,VC编译这个程序,都没有抱错误。这是为什么呢,既然默认就是noexcept,为什么可以throw? 我给析构函数加上了noexcept发现还是没有抱任何错误。为什么?
------解决思路----------------------
谁说noexcept就不能throw的?
------解决思路----------------------
这是一种"君子协定"

就就好比你定义一个变量是const,你仍然是有办法去修改他的值的
------解决思路----------------------
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 ]
------解决思路----------------------
引用:
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 ]


也就是说你可以抛,但是抛不出去,一抛程序就挂了。
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: