下面是一些代码,我写的(使用GCC的__restrict__
延伸到C++):* restrict/* __ restrict__如何在C/C++中工作?
#include <iostream>
using namespace std;
int main(void) {
int i = 7;
int *__restrict__ a = &i;
*a = 5;
int *b = &i, *c = &i;
*b = 8;
*c = 9;
cout << **&a << endl; // *a - which prints 9 in this case
return 0;
}
或者,C版(如果C++版本尚不清楚由于使用的扩展,它每一个流行的C++编译器支持),使用GCC:
#include <stdio.h>
int main(void) {
int i = 7;
int *restrict a = &i;
*a = 5;
int *b = &i, *c = &i;
*b = 8;
*c = 9;
printf("%d \n", **&a); // *a - which prints 9 in this case
return 0;
}
从我读过,如果我这样做*a = 5
,它改变了他,a
,所指向的内存值;在那之后,他指向的内存不应该被除a
之外的其他人修改,这意味着这些程序是错误的,因为b
和c
之后对它进行了修改。 或者,即使b
先修改了i
,之后只有a
才能访问该内存(i
)。 我是否正确地得到它?
P.S:限制在这个程序中不会改变任何东西。有或没有限制,编译器将产生相同的汇编代码。我写这个程序只是为了澄清事情,它不是restrict
用法的好例子。 restrict
使用的一个很好的例子,你可以在这里看到:http://cellperformance.beyond3d.com/articles/2006/05/demystifying-the-restrict-keyword.html
在C++中没有'restrict';其他任何东西都是编译器扩展。 –
[人类可以通过限定符限定符生成什么?](http://stackoverflow.com/questions/1506794/what-can-human-beings-make-out-of-the-restrict-qualifier) –
@KerrekSB比在C中考虑这个程序,使用“restrict”,我问了C/C++ ......其中之一。 –