0

我很难理解restrict调用具有已经受限变量的函数的含义。

维基百科告诉我:

限制关键字是程序员给编译器的意图声明。它表示在指针的生命周期内,只有它或直接从它派生的值(例如指针 + 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

这三种情况是:

  1. 函数a不会修改任何东西,所以肯定会成立。

  2. 怎么样b,它的参数是从foo' 指针“直接派生”的吗?foo如果我修改p1or p2in ,我是否会打破我在声明中做出的承诺b

  3. 如果参数没有以任何方式受到限制,情况是否会从以前的情况发生变化c,并且我编辑例如 p2 in c

4

1 回答 1

0

以下是您做出的承诺:

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有点棘手。您无法仅根据函数签名来判断它是否正确。

于 2015-02-17T05:34:59.710 回答