Difference between C++03 throw() specifier C++11 noexcept(C++03 throw() 说明符 C++11 noexcept 之间的区别)
问题描述
throw() 和 noexcept 除了分别在运行时和编译时检查之外,还有什么区别吗?
Is there any difference between throw() and noexcept other than being checked at runtime and compile time, respectively?
这篇维基百科 C++11 文章表明 C++03 抛出说明符已弃用.
为什么是这样,noexcept 是否足以在编译时涵盖所有这些内容?
This Wikipedia C++11 article suggests that the C++03 throw specifiers are deprecated.
Why so, is noexcept capable enough to cover all that at compile time ?
[注意:我检查了这个问题和这篇文章,但无法确定弃用的确切原因.]
[Note: I checked this question and this article, but couldn't determine the solid reason for deprecation.]
推荐答案
异常说明符已被弃用,因为异常说明符通常是一个糟糕的主意.添加 noexcept 是因为它是异常说明符的一个相当有用的用法:知道函数何时不会抛出异常.因此它变成了一个二元选择:会抛出的函数和不会抛出的函数.
Exception specifiers were deprecated because exception specifiers are generally a terrible idea. noexcept was added because it's the one reasonably useful use of an exception specifier: knowing when a function won't throw an exception. Thus it becomes a binary choice: functions that will throw and functions that won't throw.
noexcept 而不是删除除 throw() 之外的所有 throw 说明符,因为 noexcept 更强大.noexcept 可以有一个编译时解析为布尔值的参数.如果布尔值为真,则 noexcept 坚持.如果布尔值为 false,则 noexcept 不会粘住,函数可能会抛出.
noexcept was added rather than just removing all throw specifiers other than throw() because noexcept is more powerful. noexcept can have a parameter which compile-time resolves into a boolean. If the boolean is true, then the noexcept sticks. If the boolean is false, then the noexcept doesn't stick and the function may throw.
因此,您可以执行以下操作:
Thus, you can do something like this:
struct<typename T>
{
void CreateOtherClass() { T t{}; }
};
CreateOtherClass 会抛出异常吗?它可能,如果 T 的默认构造函数可以.我们怎么讲?像这样:
Does CreateOtherClass throw exceptions? It might, if T's default constructor can. How do we tell? Like this:
struct<typename T>
{
void CreateOtherClass() noexcept(is_nothrow_default_constructible<T>::value) { T t{}; }
};
因此,如果给定类型的默认构造函数抛出,CreateOtherClass() 将抛出.这解决了异常说明符的主要问题之一:它们无法向上传播调用堆栈.
Thus, CreateOtherClass() will throw iff the given type's default constructor throws. This fixes one of the major problems with exception specifiers: their inability to propagate up the call stack.
你不能用 throw() 做到这一点.
You can't do this with throw().
这篇关于C++03 throw() 说明符 C++11 noexcept 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++03 throw() 说明符 C++11 noexcept 之间的区别
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
