gpt4 book ai didi

c++ - *restrict/*__restrict__ 在 C/C++ 中如何工作?

转载 作者:可可西里 更新时间:2023-11-01 18:26:48 32 4
gpt4 key购买 nike

这是我写的一些代码(使用 GCC 的 __restrict__ 扩展到 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以外的任何人修改,这意味着这些程序是错误的,因为bc 之后修改它。或者,即使 b 首先修改 i,之后只有 a 应该可以访问该内存 (i) .我理解正确了吗?

P.S:在此程序中进行限制不会改变任何内容。无论有没有限制,编译器都会产生相同的汇编代码。我写这个程序只是为了澄清事情,它不是 restrict 用法的好例子。您可以在此处查看 restrict 用法的一个很好的示例:http://cellperformance.beyond3d.com/articles/2006/05/demystifying-the-restrict-keyword.html

最佳答案

没有。

声明

*b = 8;
*c = 9;

会导致未定义的行为。

来自文档:

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.

关于c++ - *restrict/*__restrict__ 在 C/C++ 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8290666/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com