您可以使用限制-ED指针访问某些情况下,同一个对象? [英] Can you use restrict-ed pointers to access the same object in some cases?

查看:100
本文介绍了您可以使用限制-ED指针访问某些情况下,同一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数限制的定义说,这是从程序员的编译器的指针的生命周期,指针访问该对象的唯一途径的承诺。这允许编译器,优化输出,因为它知道它会被一个指针只访问,因此只能由它来改变。这意味着,如果我理解正确通常意味着程序没有重新加载的价值指针指向。

Most definitions of restrict say that it's a promise from the programmer to the compiler that for the lifetime of the pointer, the pointer is the only way that object is accessed. This allows the compiler to optimize the output, because it knows that it will be accessed only by one pointer and thus can be changed only by it. Which if I understand correctly usually means that the program doesn't have to reload the value the pointer points to.

如果这是正确的话,应该有一些例外,当限制关键字应该是即使它违背了它应如何使用意图使用。

If this is correct then there should be some exceptions when the restrict keyword should be usable even if it goes against the intent of how it should be used.

在数据指针指向指针的一生中从来没有真正改变,想到一件事是。在这种情况下,没有必要重新加载即使指针指向相同的位置中的数据,因为它们不会在指针的寿命变化。例如:

One thing that comes to mind would be when the data the pointer points to never actually changes during the lifetime of the pointer. In such case there is no need to reload the data even if the pointers point to the same location, because they don't change in the lifetime of the pointers. E.g.:

int max(int *restrict a, int *restrict b) {
  return((*a > *b) ? *a : *b);
}

int main(void) {
  int num = 3;
  int max = max(&num, &num);
}

这是即使它违背了它是如何应该被用来限制的有效利用?将使用限制这样的结果是不确定的行为的关键字?

Is this a valid use of restrict even though it goes against how it was supposed to be used? Will using the restrict keyword like this result in undefined behaviour?

推荐答案

随着埃里克说,在评论中,现在是走了,从的 C99标准草案 6.7.3.1限制的正式定义是:

As Eric says the in a comment that is now gone, the key phrase from the C99 draft standard 6.7.3.1 Formal definition of restrict is:

`If… X is also modified…`

这间pretation由这个例子中的 6.7.3.1/10 支持:

this interpretation is supported by this example in 6.7.3.1/10:

void h(int n, int * restrict p, int * restrict q, int * restrict r)
{
  int i;
  for (i = 0; i < n; i++)
    p[i] = q[i] + r[i];
}

和与code样品如下评论:

and the following comment with the code sample:

说明如何未修改的对象可以通过两种受限指针的别名。特别是,如果a和b是不相交的阵列,形式为h的呼叫(100,A,B,b)在定义的行为,因为数组b不函数h内进行修改。

illustrate how an unmodified object can be aliased through two restricted pointers. In particular, if a and b are disjoint arrays, a call of the form h(100, a, b, b) has defined behavior, because array b is not modified within function h.

所以,它似乎是你的具体的例子是定义的行为因为你没有修改 A b

So it would seem that your specific example is defined behavior since you are not modifying a or b.

这篇关于您可以使用限制-ED指针访问某些情况下,同一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆