我在cppreference上看到了以下示例。
void f(int n, int * restrict p, int * restrict q)
{
while(n-- > 0)
*p++ = *q++; // none of the objects modified through *p is the same
// as any of the objects read through *q
// compiler free to optimize, vectorize, page map, etc.
}
void g(void)
{
extern int d[100];
f(50, d + 50, d); // OK
f(50, d + 1, d); // Undefined behavior: d[1] is accessed through both p and q in f
}
在该示例中,调用f(50, d + 50, d);
是好的。
但是,我不明白,打电话给f(50, d + 1, d)
;是未定义的行为。为什么呢?
答案 0 :(得分:5)
指针上的>>> test = ['x', 'x', 'x..', 'x']
>>> for result in fun(test):
... print(result)
...
. . ... .
. . ... -
. . -.. .
. . -.. -
. - ... .
. - ... -
. - -.. .
. - -.. -
- . ... .
- . ... -
- . -.. .
- . -.. -
- - ... .
- - ... -
- - -.. .
- - -.. -
限定符意味着通过该指针访问的任何对象在该指针的生命周期内都不会通过其他指针访问。换句话说,当通过指针restrict
访问对象并在p
范围内修改对象时,只能通过该范围内的p
访问它。违反此约束会导致未定义的行为。
在p
中,f(50, d + 50, d);
将用于修改p
最多d[50]
,d[99]
将用于访问q
到d[0]
。没有重叠,所以一切都很好。
在d[49]
中,f(50, d + 1, d);
将用于修改p
最多d[1]
,d[50]
将用于访问q
到d[0]
。由于某些元素(例如,d[49]
)通过d[1]
修改并通过p
进行了阅读,因此违反了q
限定符。