明确定义了哪些指针值以进行计算? [英] What pointer values are well-defined to compute?
问题描述
我的印象是,虽然取消引用未指向有效对象的指针是UB,但只需计算此类指针就可以了.
I was under the impression that while dereferencing pointers that don't point to a valid object is UB, simply computing such pointers is fine.
但是,如果我了解 expr.add [4] 正确,事实并非如此.
However, if I'm understanding expr.add[4] correctly, that's not the case.
那么这些指针计算中哪些是定义明确的?
So which of these pointer computations are well-defined?
int a = 42;
int *p = &a;
p; // valid, and obviously ok
p++; // invalid, but ok, because one past the end of 'array' containing 1 element?
p++; // UB ?
这种情况怎么样?
int *p = nullptr;
p; // invalid, and obviously ok (considered one past the end?)
p++; // one past the end? or UB?
推荐答案
在您的第一个示例中,第一个 p ++
是定义明确的,因为非数组被视为单长度数组.
In your first example, the first p++
is well-defined, because a non-array is considered a one-length array.
这是相关的报价( basic.compound/3.4 ):
出于指针算术([expr.add])和比较([expr.rel],[expr.eq])的目的,将指针从n个元素的数组x的最后一个元素的末尾算起等效于指向x的假设数组元素n的指针,并且不是数组元素的类型T的对象被认为属于一个元素类型T的数组.
在 p ++
, p
之后,它将指向(假设的)数组的最后一个(也是唯一的)元素,该元素定义明确.它不是无效的,但可以",因为指向对象末尾的指针不是无效的指针, basic.compound/3.2 :
After p++
, p
it will point past the last (and only) element of the (hypothetical) array, which is well-defined. It is not "invalid, but ok", as pointers pointing to past the end of an object are not invalid pointers, basic.compound/3.2:
指针类型的每个值都是以下之一:
Every value of pointer type is one of the following:
-
[...]
[...]
指向对象末尾的指针
[...]
无效的指针值.
第一个示例的第二个 p ++
是UB,因为结果将指向未定义的假设(&a)[1]元素之后.
The second p++
of the first example is UB, because the result will point after the hypothetical (&a)[1] element, which is not defined.
在第二个示例中, p ++
是UB,因为只能将0添加到 nullptr
(
In your second example, p++
is UB, because only 0 can be added to a nullptr
(expr.add/4.1):
如果P评估为空指针值,而J评估为0 ,则结果为空指针值.
[...]
否则,行为未定义.
这篇关于明确定义了哪些指针值以进行计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!