使用已在当前范围内受限的受限参数调用函数

Calling function with restricted arguments that are already restricted in current scope

我无法理解 restrict 在调用函数时使用已经受限的变量的含义。

Wikipedia 告诉我:

The restrict keyword is a declaration of intent given by the programmer to the compiler. It says that for the lifetime of the pointer, only it or a value directly derived from it (such as pointer + 1) will be used to access the object to which it points.

我有这三个示例函数:

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);
}

他们中的哪一个会遵守函数 foo 声明做出的 restrict 承诺?

三种情况是:

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

  2. b怎么样,它的参数"directly derived"是来自foo的指针吗?如果我修改 b 中的 p1p2,我是否违反了我在 foo 声明中做出的承诺?

  3. 如果不以任何方式限制参数,c 中的情况是否与之前的场景有所不同,我在 c 中编辑了例如 p2?

以下是您的承诺:

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 有点棘手的原因。仅根据函数签名无法确定它是否正确。