问题描述
为什么 std :: vector
的运算符[]
,
和
和
返回
成员函数未指定为 noexcept
?
noexcept
,即使它们没有被指定为throw。 p> 标记的函数是 swap
(必须不能失败,因为异常安全通常依赖于)和 numeric_limits :: min
(不能失败,返回原始类型的常量)。
原因是实现者可能想提供其库的特殊调试版本,抛出各种未定义的行为情况,以便测试框架可以轻松地检测错误。例如,如果您使用 vector :: operator []
的超出索引,或调用 front
或返回
。一些实现想要抛出一个异常(允许它们:因为它是未定义的行为,他们可以做任何事情),但是这些函数上的标准命令 noexcept
不可能。
Why std::vector
's operator[]
, front
and back
member functions are not specified as noexcept
?
The standard's policy on noexcept
is to only mark functions that cannot or must not fail, but not those that simply are specified not to throw exceptions. In other words, all functions that have a limited domain (pass the wrong arguments and you get undefined behavior) are not noexcept
, even when they are not specified to throw.
Functions that get marked are things like swap
(must not fail, because exception safety often relies on that) and numeric_limits::min
(cannot fail, returns a constant of a primitive type).
The reason is that implementors might want to provide special debug versions of their libraries that throw on various undefined behavior situations, so that test frameworks can easily detect the error. For example, if you use an out-of-bound index with vector::operator[]
, or call front
or back
on an empty vector. Some implementations want to throw an exception there (which they are allowed to: since it's undefined behavior, they can do anything), but a standard-mandated noexcept
on those functions makes this impossible.
这篇关于为什么向量访问运算符不指定为noexcept?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!