问题描述
为什么没有指定std::vector
的operator[]
、front
和back
成员函数作为 noexcept
?
Why std::vector
's operator[]
, front
and back
member functions are not specified as noexcept
?
推荐答案
noexcept
标准的政策是只标记不能或不能 失败,但不是那些简单指定不抛出异常的.换句话说,所有具有有限域的函数(传递错误的参数,你会得到未定义的行为)都不是 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.
被标记的函数是诸如 swap
(不能失败,因为异常安全通常依赖于它)和 numeric_limits::min
(不能失败,返回一个常量原始类型).
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).
原因是实现者可能希望提供他们库的特殊调试版本,这些版本会引发各种未定义的行为情况,以便测试框架可以轻松检测到错误.例如,如果您使用带有 vector::operator[]
的越界索引,或者在空的索引上调用 front
或 back
向量.一些实现想要在那里抛出一个异常(他们被允许:因为这是未定义的行为,他们可以做任何事情),但是这些函数上的标准强制noexcept
使这成为不可能.
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!