下溢或上溢的指针会发生什么情况?

What happens to a pointer which underflows or overflows?

我有一个 class,它只是一个原始指针包装器。我在想能不能申报:

noexcept。这些运算符可能抛出的唯一原因是原始指针会抛出。所以问题是:当 -- 在已经是 0 的指针上调用时会发生什么,而当 ++ 在已达到最大值的指针上调用时会发生什么?

原始指针算法不会抛出任何东西。它只会让你搞砸自己。所以是的,你可以。

该标准在 §5.7/4 中规定:

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. [...] Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behaviour is undefined.

(强调我的)

在 §5.7/5 中可以找到类似的减法引用。因此,鉴于上溢和下溢是指针的特殊情况,它们超出了它们最初指向的对象的边界,因此行为将是未定义的。

我想说您可以声明这些函数 noexcept

附带说明一下,标准库中的类指针类型,如 std::unique_ptr,不会将可能导致上述未定义行为的函数定义为 noexcept(例如 operator[] for std::unique_ptr) 因为一些实现决定在调试模式下抛出异常。