gpt4 book ai didi

c++ - std::string::compare(const char*) 可以抛出异常吗?

转载 作者:IT老高 更新时间:2023-10-28 23:21:37 25 4
gpt4 key购买 nike

这是过载 (4) here

在“异常”部分,重载 2、3、5、6(具有 pos1 和/或 pos2 参数)被命名为 throwing std::out_of_range .

重载(4)没有“pos”参数,但是没有标注noexcept .

是否抛出取决于实现?

在 GCC 7 的 libstdc++ 中,它调用 char_traits<char>::lengthchar_traits<char>::compare .这些似乎不能扔,但没有标记noexcept .

最佳答案

除了析构函数、交换函数、移动构造函数和移动赋值运算符之外,标准仅在函数具有 wide contract 时才标记函数 noexcept ,即它没有先决条件。此重载要求参数是一个以空字符结尾的字符串,因此标准不会将其标记为 noexcept

有理数在 N3248 中指定:

Functions marked noexcept are difficult to test

When a function is marked with noexcept it becomes impossible to flag test failures, notably in test drivers, by throwing an exception. A common example would be code that validates preconditions on entry to a function:

T& std::vector<T>::front() noexcept {
assert(!this->empty());
return *this->data();
}

When validating such defensive checks from a test driver, a reasonable approach is to register an assert-handler that throws a well-defined precondition-violated exception, which the test driver catches to ensure that the appropriate asserts are indeed in place.

...

Now we might argue that calling the function out-of-contract, when the vector is empty, is undefined behavior so we should not expect any guarantees. The problem is that undefined behavior is being specified by the library; to the compiler, this code is perfectly well defined and, if assert throws an exception, the program must terminate in a well-specified manner, thwarting the test driver.

Note that the issue here is not that we are using assertions to find bugs in our own library implementations, but rather in user code that incorrectly calls into our library. If we remove the ability to test these defensive assertions, we may get them wrong, and thus put our users at risk for committing far more serious errors than propagating an unexpected exception.


顺便说一句,由于 [res.on.exception.handling]/5 :

An implementation may strengthen the exception specification for a non-virtual function by adding a non-throwing exception specification.

... libstdc++libc++ 可以自由地标记这个重载 noexcept

关于c++ - std::string::compare(const char*) 可以抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56971781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com