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

标签 c++ c

这是我写的一些代码(使用 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/

相关文章:

c++ - x64 位 Windows 上的 ExpandEnvironmentStrings( ... ) 正在将 %programfiles% 扩展到 x86 路径

c++ - 为什么在这种情况下使用 int *arr = new int [number]?

c++ - Unix(大端)代码和Linux(小端)上的相同代码,创建不同的输出直径文件

c++ - 为什么我的二进制搜索需要额外的比较? log2(N)+1

c - 指向单引号字符串的字符指针数组打印字符串的最后 4 个字节

c++ - c++ 1z模块是否会取代Windows上对dllimport dllexport的需求

c++ - 动态转换和静态转换的奇怪行为

c++ - 获取错误:在抛出 'std::bad::alloc' what(): std::bad_alloc 的实例后调用终止

c - OpenCL - 双重原子操作 - 工作到极限

c - 将不同类型的指针分配给现有内存