为什么std :: exception析构函数不是noexcept [英] Why is the std::exception destructor not noexcept
问题描述
C ++ 11的析构函数 < a href = http://en.cppreference.com/w/cpp/error/exception rel = nofollow noreferrer> std :: exception
基类不是 noexcept
,因此(理论上)可能会引发异常,从而对其所有派生类(包括 std :: bad_alloc
和 std :: runtime_error
)。 C ++ 98 std :: exception
的析构函数具有 throw()
异常规范,表明它是不允许抛出异常。为什么会有所不同?为什么现在允许引发异常?鉴于 std :: exception
构造器现在是 noexcept
:您可以安全地构造这样的对象,但是不能安全地销毁它:与正常情况相反行为。
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.
让异常类的析构函数抛出异常通常是灾难性的。是什么会导致 std :: exception ::〜exception
引发异常?
Having the destructor of an exception class throw an exception is usually disastrous. What can cause std::exception::~exception
to throw an exception?
推荐答案
实际上是 noexcept(true)
。从C ++ 11开始,对于析构函数,没有明确指定异常的规定被认为是 noexcept(true)
。
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)
.
除非没有异常说明如果明确提供,则将异常规范视为隐式声明的析构函数将使用的规范(请参见下文)。在大多数情况下,这是
noexcept(true)
。因此,必须将抛出的析构函数显式声明为noexcept(false)
。 (自C ++ 11起)
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 declarednoexcept(false)
. (since C++11)
这篇关于为什么std :: exception析构函数不是noexcept的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!