为何C++20中针对指针的std::midpoint未被标记为noexcept?
std::midpoint marked noexcept? Great question! Let’s break down the key reasons behind this C++ standard design choice, even though GCC and Clang do mark their pointer overload implementations as noexcept:
Preconditions and Debug Guardrails
The pointer version ofstd::midpointhas a critical precondition: the two input pointers must point to elements of the same array (or one position past the end of that array). If you violate this, the behavior is undefined. While the standard doesn’t require implementations to check for this, many compilers add debug-mode assertions to catch invalid pointer pairs. These assertions usually terminate the program (viastd::abort, for example) instead of throwing exceptions, but the committee chose not to addnoexceptto avoid giving developers the false impression that any use of the function—even those breaking the preconditions—will safely avoid exceptions or abnormal termination.Portability Across Edge Case Platforms
Modern systems use flat memory models where pointer arithmetic is straightforward, but the C++ standard has to account for all conforming platforms, including legacy or specialized systems with non-flat memory. On some of these platforms, calculating the midpoint of two pointers could trigger hardware-level exceptions or implementation-defined behavior that might surface as exceptions. Omittingnoexceptensures the standard doesn’t restrict how these platforms handle such edge cases.Alignment with Pointer Operation Norms
The standard generally avoids marking pointer-related functions asnoexceptwhen their validity depends on preconditions around pointer safety. This follows the same logic as other pointer utilities: for example,std::advancefor pointers isn’t markednoexcepteither, even though it’s just pointer arithmetic, because violating its bounds preconditions leads to undefined behavior.
It’s important to note that in valid use cases (where pointers meet the preconditions), production builds of most compilers will execute the pointer std::midpoint without throwing exceptions. The lack of noexcept in the standard is more about maintaining portability and avoiding misleading guarantees than indicating the function can throw when used correctly.
内容的提问来源于stack exchange,提问作者VainMan

