restrict pointer

来源:互联网 发布:ubuntu 查看安装目录 编辑:程序博客网 时间:2024/05/01 15:49

http://hi.baidu.com/ilotus_y/blog/item/bed71ed3c6d7f532960a16fc.html

 

__restrict / restrict

这是从IBM的一个网站上看来的:

restrict只可以用在指针身上。如果一个指针被restrict修饰,那么就在它(这个指针)和它所指向的对象之间建立了一种特殊的联系──只能用这个指针或者这个指针的表达式来访问这个对象的值。

一个指针指向一个内存地址。同一块内存可以由多个指针来访问并在程序运行时修改它(这块内存)。restrict告诉编译器,如果一块由一个被restrict修饰的指针所指向的内存被修改了,那么没有其它的指针可以来访问这块内存。编译器可能会选择一种方式来优化代码中调用被restrict修饰的指针的部分,这可能导致错误发生。程序员有责任来确保正确地按照他们所设想的来使用被restrict修饰的指针,否则的话,可能会发生意想不到的结果。

如果一块特定的内存区没有被修改,那么它可以被多个restrict指针(被restrict修饰的指针)所指代(或者叫做引用或访问)。

另外,restrict指针的赋值是有限制的,这一点在函数调用和嵌套块(nested block)之间是没有区别的。在包含restrict指针的块中,只能将外层的restrict指针的值赋给内层的restrict指针,在同层内不可以相互赋值,当然在外层不可能赋以内层的值。一个例外是,当一个声明restrict指针的代码快执行完后,这个restrict指针所指的内存就可以被其它的指针访问了(因为那个restrict是那个代码块的局部变量,当执行完那个代码块后,这个指针也就不复存在了)。

 

 

原文:

The restrict type qualifier may only be applied to a pointer. A pointer declaration that uses this type qualifier

establishes a special association between the pointer and the object it accesses, making that pointer and 

expressions based on that pointer, the only ways to directly or indirectly access the value of that object.

 

A pointer is the address of a location in memory. More than one pointer can access the same chunk of 

memory and modify it during the course of a program. The restrict type qualifier is an indication to the 

compiler that, if the memory addressed by the restrict-qualified pointer is modified, no other pointer will 

access that same memory. The compiler may choose to optimize code involving restrict-qualified pointers in a 

way that might otherwise result in incorrect behavior. It is the responsibility of the programmer to ensure that 

restrict-qualified pointers are used as they were intended to be used. Otherwise, undefined behavior may 

result.

 

If a particular chunk of memory is not modified, it can be aliased through more than one restricted pointer.

 

The following example shows restricted pointers as parameters of foo(), and how an unmodified object can 

be aliased through two restricted pointers.

 

void foo(int n, int * restrict a, int * restrict b, int * restrict c)

{

    int i;

    for (i = 0; i < n; i++)

    a[i] = b[i] + c[i];

}

 

Assignments between restricted pointers are limited, and no distinction is made between a function call and 

an equivalent nested block.

{

    int * restrict x;

    int * restrict y;

    x = y; // undefined

    {

        int * restrict x1 = x; // okay

             int * restrict y1 = y; // okay

        x = y1; // undefined

    }

}

 

In nested blocks containing restricted pointers, only assignments of restricted pointers from outer to inner 

blocks are allowed. The exception is when the block in which the restricted pointer is declared finishes 

execution. At that point in the program, the value of the restricted pointer can be carried out of the block in 

which it was declared.

原创粉丝点击