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 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!