C++11 异常的析构函数现在允许抛出吗?

标签 c++ exception c++11 destructor c++98

知道为什么 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-id T if and only if T 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, and f has the exception-specification noexcept(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/

相关文章:

c++ - 如何检查 std::vector<std::string> 的元素是否以某个子字符串开头?

c++ - Emacs + C/C++ + Doxygen : Alternative to doxymacs? 使用 yasnippet?

c++ - 从 arma::subvec 类型的右值初始化类型的非常量引用无效

c++ - 阻止 QListView 删除拖放条目

c++ - std::shared_ptr<Parent> 到 std::shared_ptr<Child>

exception - Apache Camel 错误因为必须在 : process? 上指定 ref

hibernate - 登录应用程序异常

asp.net-mvc - 点击错误: An instance of IControllerFactory was found in the resolver as well as a custom registered provider

c++ - c++11 中任意大小整数的最低 31 位

C++0x 错误 : variable 'std::packaged_task<int> pt1' has initializer but incomplete type