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?


基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01