Why vector access operators are not specified as noexcept?(为什么不将向量访问运算符指定为 noexcept?)
问题描述
为什么没有指定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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么不将向量访问运算符指定为 noexcept?


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01