*限制/ * __ restrict__如何在C/C++中运行?

前端之家收集整理的这篇文章主要介绍了*限制/ * __ restrict__如何在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之外,其他任何人都不应该修改他所指向的内存,这意味着这些程序是错误的,因为b和c之后会对其进行修改.
或者,即使b首先修改i,之后只有a应该访问该内存(i).
我得到的正确吗?

P.S:限制在这个程序中不会改变任何东西.无论有没有限制,编译器都会生成相同的汇编代码.我写这个程序只是为了澄清事情,它不是限制使用的好例子.限制使用的一个很好的例子,你可以在这里看到: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.

原文链接:https://www.f2er.com/c/118554.html

猜你在找的C&C++相关文章