gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:20:34 25 4
gpt4 key购买 nike

我无法理解 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 promise ?

这三种情况是:

  1. 函数a不会修改任何内容,因此这肯定成立。

  2. b 怎么样,它的参数是从 foo 的指针“直接派生”的吗?如果我修改 b 中的 p1p2 ,我是否会违背在 foo 声明中做出的 promise ?

  3. 如果参数不受任何方式限制,并且我在 c 中编辑 p2,则 c 中的情况与之前的情况相比是否会发生变化?

最佳答案

以下是您做出的 promise :

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

除非您知道这些函数的作用以及它们的调用方式,否则您无法确定您所做的 promise 是否正确。

例如,这是错误的:

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

关于使用已在当前范围内受到限制的受限参数调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28530162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com