首页 > 解决方案 > 初始化新指针时使用“restrict”实际上有什么作用吗?

问题描述

我一直在阅读有关restrict关键字的信息,并且我看到的每个示例在定义函数时都使用它。

void foo (int *restrict bar, float *restrict baz);

我一直在阅读有关它的文章,想知道这是否有效。

int main()
{
    int *restrict bar = malloc(sizeof(int));
    //... code using bar
    return 0;
}

我用 gcc 对其进行了测试,但没有收到任何编译器警告,但它实际上会任何事情吗?编译器是否会发现这个指针在它的生命周期内不会重叠并且它不会被任何其他指针共享,或者它只会在定义函数时使用?

标签: cpointers

解决方案


main 中受限的“bar”告诉编译器不会通过任何其他指针引用数据。根据 main 的作用,它可能有助于优化“main”。如果 的 唯一 的 操作bar是 在 函数foo中 , 就 没有 必要 做 它restrict.

附带说明一下,在 Linux/gcc 上,“malloc”标记为__attribute__ ((__malloc__)),它告诉编译器返回的值是限制指针,这将允许编译器执行所需的优化(如果相关)。请参阅:了解 malloc.h 的区别:__attribute_malloc__ https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html

malloc

This tells the compiler that a function is malloc-like, i.e., that the pointer P 
returned by the function cannot alias any other pointer valid when the function
returns, and moreover no pointers to valid objects occur in any storage addressed by P.

Using this attribute can improve optimization. Compiler predicts that
a function with the attribute returns non-null in most cases.
Functions like malloc and calloc have this property because they
return a pointer to uninitialized or zeroed-out storage. However,
functions like realloc do not have this property, as they can return a
pointer to storage containing pointers.

推荐阅读