ptrdiff_t太小? [英] ptrdiff_t too small?
问题描述
我一直想知道:不是 ptrdiff_t
应该能够保持任何两个指针的差异按定义?当两个指针太远时,它如何失败? (我不指向任何特定的语言...我指的是具有这种类型的所有语言。)
I've always wondered: isn't ptrdiff_t
supposed to be able to hold the difference of any two pointers by definition? How come it fails when the two pointers are too far? (I'm not pointing at any particular language... I'm referring to all languages which have this type.)
(例如,减去指针地址<$当你有32位指针,并溢出符号位...)时,从地址 0xFFFFFFFF
的字节指针返回c $ c> 1
(e.g. subtract the pointer with address 1
from the byte pointer with address 0xFFFFFFFF
when you have 32-bit pointers, and it overflows the sign bit...)
推荐答案
不,不是。
$ 5.7 [expr.add] (从n3225 - C ++ 0x FCD)
当减去同一数组对象的两个指针时,结果是两个阵列元素的下标的差。结果的类型是实现定义的符号整型;这个类型应该是< cstddef>
头中的std :: ptrdiff_t
)。对于任何其他算术溢出,如果结果不适合提供的空间,行为是未定义的。
换句话说,如果表达式P
和Q
分别指向<$ c $数组对象的i -th和 j
- 元素,表达式(P) - (Q)如果值适合类型为
和std :: ptrdiff_t $ c $的对象,则
的值为i - j
c>。此外,如果表达式P
指向数组对象的元素或者指向数组对象的最后一个元素,并且表达式Q
指向同一数组对象的最后一个元素,表达式((Q)+1) - (P)
c $ c>((Q) - (P))+ 1- ((P) - ((Q)+1))
,并且如果表达式P
指向一个超过数组对象的最后一个元素,即使表达式(Q)+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 asstd::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 expressionsP
andQ
point to, respectively, thei
-th andj
-th elements of an array object, the expression(P)-(Q)
has the valuei − j
provided the value fits in an object of typestd::ptrdiff_t
. Moreover, if the expressionP
points either to an element of an array object or one past the last element of an array object, and the expressionQ
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 expressionP
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
。另请注意,如果指针指向同一对象内,则只能减去指针。
Note the number of times undefined
appears in the paragraph. Also note that you can only subtract pointers if they point within the same object.
这篇关于ptrdiff_t太小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!