为什么向量访问运算符不指定为noexcept? [英] Why vector access operators are not specified as noexcept?

查看:168
本文介绍了为什么向量访问运算符不指定为noexcept?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 std :: vector 运算符[] 返回成员函数未指定为 noexcept

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆