我很难理解restrict
用已受限制的变量调用函数意味着什么。
维基百科告诉我:
strict关键字是程序员向编译器给出的意图声明。它表示在指针的整个生命周期内,将仅使用它或直接从其派生的值(例如指针+ 1)来访问它所指向的对象。
我有以下三个示例函数:
void a(int const *p1, int const *p2) {
...
}
void b(int *restrict p1, int *restrict p2) {
...
}
void c(int *p1, int *p2) {
...
}
我会从函数中分别调用它们
foo(int *restrict p1, int *restrict p2) {
a(p1, p2);
b(p1, p2);
c(p1, p1+1);
}
他们中的哪一个会信守restrict
函数foo
声明的承诺?
这三种情况是:
函数a
不做任何修改,因此肯定会成立。
怎么样b
,它的参数是从foo
的指针“直接派生”的?foo
如果修改p1
或p2
,我是否会放弃在声明中给出的诺言b
?
c
如果不以任何方式限制参数,情况是否会从上一场景发生变化,例如,我在中编辑p2 c
?
这是您的承诺:
void foo(int *restrict p1, int *restrict p2) {
// a() can't modify p1[...] or p2[...]
a(p1, p2);
// b() CAN modify p1[...] or p2[...]
// Note that you are still making this promise if you don't use
// "restrict" in the declaration of b()
b(p1, p2);
// c() CAN modify p1[...] but not p2[...]
c(p1, p1+1);
}
您不能确定所作出的承诺是正确的,除非您知道函数的作用以及如何调用它们。
例如,这是错误的:
int global;
void a(int const *p1, int const *p2) {
// Since p1 == &global, we can break the promise here
// by accessing *p1 through the name "global"...
// Even though this function is perfectly okay by itself!
global = 5;
}
void foo(int *restrict p1, int *restrict p2) {
// We have a promise that a() won't modify p1[...]
// BECAUSE: "restrict" promises that all p1 modifications
// go through p1, since p1 is passed "const" a() is not
// supposed to modify *p1, but p1 = &global, and a() modifies
// global... BOOM!
// Even though this function is perfectly okay by itself...
a(p1, p2);
}
int main() {
int y;
// Illegal! Once you pass &global to foo(), BOOM!
foo(&global, &y);
}
这就是为什么restrict
有些棘手的原因。仅凭功能签名就无法确定它是否正确。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句