c++ - C++11 中弃用的 throw-list

标签 c++ c++11 throw

正如我在 cppreference 中看到的那样,经典的“抛出”声明列表现在在 C++11 中已弃用。离开这个机制的原因是什么?我应该如何指定哪些异常会引发我的函数?

最佳答案

更详细的推理见:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3051.html

As expressed in the national body comment above, exception specifications have not proven useful in practice. There are numerous discussions of the problems with exception specifications in C++ (see, e.g., [Sutter02], [Boost03]), but the main issues are:

  • Run-time checking: C++ exception specifications are checked at runtime rather than at compile time, so they offer no programmer guarantees that all exceptions have been handled. The run-time failure mode (calling std::unexpected()) does not lend itself to recovery.
  • Run-time overhead: Run-time checking requires the compiler to produce additional code that also hampers optimizations.
  • Unusable in generic code: Within generic code, it is not generally possible to know what types of exceptions may be thrown from operations on template arguments, so a precise exception specification cannot be written.

In practice, only two forms of exception-throwing guarantees are useful: an operation might throw an exception (any exception) or an operation will never throw any exception. The former is expressed by omitting the exception-specification entirely, while the latter can be expressed as throw() but rarely is, due to performance considerations.

[N3050] introduces a new kind of exception specification, noexcept, the specifies that the function will not throw any exceptions. Unlike throw(), noexcept does not require the compiler to introduce code to check whether an exception is thrown. Rather, if a function specified as noexcept is exited via an exception, the result is a call to std::terminate().

With the introduction of noexcept, programmers can now express the two kinds of exception guarantees that are useful in practice, without additional overhead. This paper therefore proposes to deprecate "dynamic" exception specifications, i.e., those that are written as throw(type-id-listopt).

关于c++ - C++11 中弃用的 throw-list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13841559/

相关文章:

c++ - 为什么必须链接库并设置包含目录

c++ - constexpr 用于派生类中空初始化的构造函数

c++ - `void func() throw(type)` 有什么意义?

java - 无法抛出 IllegalArgumentException

javascript - `throw ' foo '`, ` throw Error ('foo' )`, ` throw new Error ('foo' )` 有什么区别?

c++ - 函数在 C++ 中不保持独立?

c++ - 编写 shell - 如何确定不同 exec 调用的可执行路径和文件名

c++ - 成员函数和复制构造函数

C++ 错误 : Undefined symbols for architecture x86_64

c++ - 为什么有变异的 Boost.Range 算法的 const 重载?