知道为什么 virtual ~exception() throw() 在 C++98 中, 但 virtual ~exception() 在 C++11 中?
允许 C++11 抛出类 exception
的析构函数的设计决策是什么?
来自 here :
c++98:
class exception {
public:
exception () throw();
exception (const exception&) throw();
exception& operator= (const exception&) throw();
virtual ~exception() throw();
virtual const char* what() const throw();
}
c++11:
class exception {
public:
exception () noexcept;
exception (const exception&) noexcept;
exception& operator= (const exception&) noexcept;
virtual ~exception();
virtual const char* what() const noexcept;
}
最佳答案
What's the desing decision makes C++11 allow to throw in the destructor of the class
exception
?
没有这样的设计决定(幸运的是!)。在 C++11 中,即使是显式声明的析构函数默认也被限定为 noexcept
。这可以从 C++11 标准的第 12.4/3 段中得到证明:
A declaration of a destructor that does not have an exception-specification is implicitly considered to have the same exception-specification as an implicit declaration (15.4).
从第 15.4/14 段开始,它指定了隐式声明的异常规范:
An inheriting constructor (12.9) and an implicitly declared special member function (Clause 12) have an exception-specification. If
f
is an inheriting constructor or an implicitly declared default constructor, copy constructor, move constructor, destructor, copy assignment operator, or move assignment operator, its implicit exception-specification specifies the type-idT
if and only ifT
is allowed by the exception-specification of a function directly invoked by f’s implicit definition;f
allows all exceptions if any function it directly invokes allows all exceptions, andf
has the exception-specificationnoexcept(true)
if every function it directly invokes allows no exceptions.
以上两段一起保证(鉴于您引用的 exception
析构函数的声明)exception
的析构函数不会抛出。
C++11 标准的第 18.8.1/7-8 段也明确说明了这一点:
virtual ~exception();
7 Effects: Destroys an object of class exception.
8 Remarks: Does not throw any exceptions.
请注意,动态异常规范(例如 throw()
)在 C++11 中已弃用。根据附件 D 的第 D.4/1 节:
The use of dynamic-exception-specifications is deprecated.
关于C++11 异常的析构函数现在允许抛出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16540725/