Why is the std::exception destructor not noexcept [duplicate]

早过忘川 提交于 2019-12-24 17:15:04

问题


The destructor of the the C++11 std::exception base class is not noexcept, and thus may (in theory) throw an exception, which consequent relaxed permission for all its derived classes (including std::bad_alloc and std::runtime_error). The destructor of the C++98 std::exception however had a throw() exception specification, indicating it was not permitted to throw exceptions. Why the difference? Why is it now permitted to throw exceptions? The permission is particularly odd given that the std::exception constructors are now noexcept: you can safely construct such an object, but you can not safely destroy it: the opposite of the normal behaviour.

Having the destructor of an exception class throw an exception is usually disastrous. What can cause std::exception::~exception to throw an exception?


回答1:


It is noexcept(true) indeed. Since C++11, for destructors with no exception specification explicitly provided the exception specification is considered to be noexcept(true).

Except that if no exception specification is explicitly provided, the exception specification is considered to be one that would be used by the implicitly-declared destructor (see below). In most cases, this is noexcept(true). Thus a throwing destructor must be explicitly declared noexcept(false). (since C++11)




回答2:


[res.on.exception.handling]/3:

Destructor operations defined in the C++ standard library shall not throw exceptions. Every destructor in the C++ standard library shall behave as if it had a non-throwing exception specification.



来源:https://stackoverflow.com/questions/50025862/why-is-the-stdexception-destructor-not-noexcept

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!