restrict是C99新增的一个关键字,其主要目的是用来优化用的。它只能修饰指针。该关键字告诉编译器,哪些指针引用是可以优化的,
其方法是指明指针指向的对象,在函数中只通过该指针进行访问。
它的英文定义是: It can be applied only to pointers, and it indicates that a pointer is the sole initial means of accessing a data object.
以我通俗的理解,它就是说被具有restrict修饰的指针的数据对象,只能被该指针修改,从而编译器可以进行一些优化措施。
int ar[10]; int * restrict restar = (int *) malloc(10 * sizeof(int)); int * par = ar;
for (n = 0; n < 10; n++) { par[n] += 5; restar[n] += 5; ar[n] *= 2; par[n] += 3; restar[n] += 3; } restar指针是restrict类型,par指针就不是,因为par即没有初始化也不是唯一访问ar数组的变量。 那么,上面的程序,因为restar是唯一反问数据块的指针,所以编译器可以对它优化为一条语句, restar[n] += 8; /* ok replacement */ 而par就不可以, par[n] += 8; / * gives wrong answer */
void f (const int* pci, int *pi;); // is *pci immutable?
{
(*pi)+=1; // not necessarily: n is incremented by 1
*pi = (*pci) + 2; // n is incremented by 2
}
int n;
f( &n, &n);
In this example, both pci and pi point to the same variable, n. You can't change n's value through pci but you can change it using pi. Therefore, the compiler isn't allowed to optimize memory access for *pci by preloading n's value. In this example, the compiler indeed shouldn't preload n because its value changes three times during the execution of f(). However, there are situations in which a variable is accessed only through a single pointer. For example:
FILE *fopen(const char * filename, const char * mode);
The name of the file and its open mode are accessed through unique pointers in fopen(). Therefore, it's possible to preload the values to which the pointers are bound. Indeed, the C99 standard revised the prototype of the function fopen() to the following:
/* new declaration of fopen() in <stdio.h> */
FILE *fopen(const char * restrict filename,
const char * restrict mode);
Similar changes were applied to the entire standard C library: printf(), strcpy() and many other functions now take restrict pointers:
int printf(const char * restrict format, ...);
char *strcpy(char * restrict s1, const char * restrict s2);
C++ doesn't support restrict yet. However, since many C++ compilers are also C compilers, it's likely that this feature will be added to most C++ compilers too.
http://www.cnblogs.com/hustcat/articles/1510736.html