C ++ 03之间的区别throw()说明符C ++ 11 noexcept [英] Difference between C++03 throw() specifier C++11 noexcept
问题描述
除了分别检查运行时和编译时间之外, throw()
和 noexcept
之间是否还有其他区别?
Is there any other difference between throw()
and noexcept
apart from being checked runtime and compile time respectively ?
维基百科C ++ 11 文章建议不推荐使用C ++ 03 throw说明符。
为什么这样, noexcept
足够覆盖编译时的所有内容?
Wikipedia C++11 article suggests that C++03 throw specifiers are deprecated.
Why so, is noexcept
capable enough to cover all that at compile time ?
[注意:我提到此问题和这篇文章,但无法得到贬抑的坚实理由。]
[Note: I referred this question and this article, but couldn't got the solid reason of 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
可以有一个参数,编译时解析成一个布尔值。如果布尔值为true,那么 noexcept
会停止。如果布尔值为假,那么 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.
可以这样做:
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()
给定类型的默认构造函数throws。这修复了异常说明符的一个主要问题:它们不能传播调用堆栈。
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 )
。
这篇关于C ++ 03之间的区别throw()说明符C ++ 11 noexcept的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!