c - 初始化新指针时使用“restrict”实际上有什么作用吗?
问题描述
我一直在阅读有关restrict
关键字的信息,并且我看到的每个示例在定义函数时都使用它。
void foo (int *restrict bar, float *restrict baz);
我一直在阅读有关它的文章,想知道这是否有效。
int main()
{
int *restrict bar = malloc(sizeof(int));
//... code using bar
return 0;
}
我用 gcc 对其进行了测试,但没有收到任何编译器警告,但它实际上会做任何事情吗?编译器是否会发现这个指针在它的生命周期内不会重叠并且它不会被任何其他指针共享,或者它只会在定义函数时使用?
解决方案
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.
推荐阅读
- python - 在 Cassandra 中使用 DataStax 模型操作批量插入多个表
- deep-learning - 深度学习:验证数据集是否用于训练?
- laravel - Laravel 和 vue 无限加载器和分页问题
- c - 在C中替换矩阵中的元素
- sql - SSMS 创建具有特定列属性的视图
- python-3.x - 终端命令安装模块的导入模块
- install4j - Install4j SQL 脚本语句分隔符
- reactjs - 在已经调用 3rd 方 API 之后,如何为每个单独的映射项添加附加属性?
- java - 如何在 spring 中覆盖 application-default.yml 值
- mariadb - 增加 mariaDB 中索引键的最大字符数限制