Standard library functions can throw exceptions 标准库函数何时可能抛出异常?

huangapple go评论62阅读模式
英文:

When can the standard library functions throw exceptions?

问题

我有困难理解标准库中哪些函数可能会引发异常,以及在何种情况下可能会引发异常。

有些函数是noexcept,那么它们就不会引发异常,但是如果我查看例如std::string::operator[]():https://en.cppreference.com/w/cpp/string/basic_string/operator_at,这个操作符并不是noexcept,但页面上没有提到异常(同样也是这里,所以这与std::basic_string是一个模板无关)。

我能否假设如果页面上没有列出异常,那么这个函数不会引发异常(但由于某些原因未被标记为noexcept)?或者是函数可能引发实现定义的异常?当列出异常时,它们是否是唯一可能引发的异常?

编辑:

  • 有人指出我应该参考实际的标准而不是cppreference来解决我的问题,并友好地提供了一个相关链接。

  • 在我的示例中,相关页面应该是这个:https://eel.is/c++draft/string.access,明确指出operator[]()ThrowsNothing

  • 话虽如此,在下面几行是front(),它不是noexcept,并且在描述中没有Throws条目,所以我的问题仍然存在。

英文:

I'm having trouble understanding which functions from the standard library can throw exceptions, and if so which and when.

Some functions are noexcept, in which case ok they don't, but if I look for example at std::string::operator[](): https://en.cppreference.com/w/cpp/string/basic_string/operator_at, the operator is not noexcept yet the page says nothing about exceptions (and same here so it should have nothing to do with std::basic_string being a template).

Can I assume that if no exception is listed on a page then it means that the function cannot throw (but was not marked as noexcept for some reason)? Or does it mean the function can throw implementation-defined exceptions? And when exceptions are listed, are they the only ones that can be thrown?

Edit:

  • Someone remarked that I should refer to the actual standard and not cppreference for my question, and kindly provided me a relevant link.

  • In my example the relevant page would be this one: https://eel.is/c++draft/string.access which explicitly states Throws: Nothing for operator[]()

  • That being said, a few lines below is front(), which is not noexcept and doesn't have a Throws entry in its description, so my question still stands

答案1

得分: 1

有时候你必须看出字里行间。

字符串 operator[] 具有前提条件,索引必须有效。cppreference说:

> 如果 pos > size(),行为是未定义的。

未定义行为包括抛出异常。实际上,一些实现在调试模式下会抛出越界异常。

数学函数,如 std::abs,最初来自C库。尽管C库不会抛出异常,但它也不会为任何函数声明noexcept,为了保持兼容性,C++也不这样做。

英文:

Sometimes you have to read between the lines.

The string operator[] has a precondition that the index must be valid. cppreference says:

> If pos > size(), the behavior is undefined.

Undefined behavior includes throwing exceptions. And, in fact, some implementations will throw an out-of-range exception in debug mode.

The math functions, like std::abs, originally come from the C library. Even though the C library doesn't throw exceptions, it also doesn't say noexcept for any of the functions, so to be compatible neither does C++.

huangapple
  • 本文由 发表于 2023年5月17日 15:54:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269739.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定