当不抛出零成本时,noexcept没用吗? [英] Is noexcept useless when not throwing is zero-cost?
问题描述
如果您的实现具有零成本(如果未抛出任何异常)异常模型,则 noexcept
说明符是否无用?缺少 noexcept
会导致后果的例子是什么?
Is the noexcept
specifier useless if your implementation has a zero-cost (if nothing is thrown) exception model? What is an example where lacking noexcept
has a consequence?
推荐答案
如果您的实现具有零成本(如果未抛出任何异常)异常模型,则
noexcept
指定符是否无用?
否,即使异常对性能完全没有影响, noexcept
还是有用的。
No, noexcept
would be useful even if exceptions had no performance impact at all.
一个例子是 noexcept
可以表示可以使用哪种算法。例如,使用 std :: move_if_noexcept
或许多标准 type_traits 的行为可能会有所不同,具体取决于 noexcept
的存在。
One example is that noexcept
can signal which algorithm can be used. For example algorithms that use std::move_if_noexcept
or many of the standard type_traits could behave differently depending on the presence of noexcept
.
这可能对 std :: vector之类的常用功能产生重大影响code>如果您元素的move构造函数不是
noexcept
,则速度会慢得多。如果移动构造函数不是 noexcept
, std :: vector
将在重新分配时复制所有元素,而不是移动它们。强有力的例外保证。
This can have a significant impact for common features like std::vector
which will be much slower if you elements' move constructor isn't noexcept
. std::vector
will copy all elements when reallocating instead of moving them if the move constructor is not noexcept
to preserve the strong exception guarantee.
这篇关于当不抛出零成本时,noexcept没用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!