gpt4 book ai didi

c++ - ptrdiff_t 太小?

转载 作者:IT老高 更新时间:2023-10-28 22:08:49 33 4
gpt4 key购买 nike

我一直想知道:ptrdiff_t 是否应该能够保存任意两个指针的差异定义?两个指针太远怎么会失败? (我不是指任何特定的语言...我指的是所有具有这种类型的语言。)

(例如,当您有 32 位指针时,从地址为 0xFFFFFFFF 的字节指针中减去地址为 1 的指针,它会溢出符号位...)

最佳答案

不,不是。

$5.7 [expr.add] (from n3225 - C++0x FCD)
When two pointers to elements of the same array object are subtracted, the result is the difference of the subscripts of the two array elements. The type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as std::ptrdiff_t in the <cstddef> header (18.2). As with any other arithmetic overflow, if the result does not fit in the space provided, the behavior is undefined. In other words, if the expressions P and Q point to, respectively, the i-th and j-th elements of an array object, the expression (P)-(Q) has the value i − j provided the value fits in an object of type std::ptrdiff_t. Moreover, if the expression P points either to an element of an array object or one past the last element of an array object, and the expression Q points to the last element of the same array object, the expression ((Q)+1)-(P) has the same value as ((Q)-(P))+1 and as -((P)-((Q)+1)), and has the value zero if the expression P points one past the last element of the array object, even though the expression (Q)+1 does not point to an element of the array object. Unless both pointers point to elements of the same array object, or one past the last element of the array object, the behavior is undefined.

注意次数undefined出现在段落中。另请注意,如果指针指向同一个对象,则只能减去它们。

关于c++ - ptrdiff_t 太小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4860086/

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