限制结构体内关键字和指针

19

通过如下使用 restrict 关键字:

int f(int* restrict a, int* restrict b);

我可以指示编译器,让它知道数组a和b不会重叠。假如我有一个结构体:

struct s{
(...)
int* ip;
};

编写一个函数,接受两个struct s对象:

int f2(struct s a, struct s b);

我该如何在这种情况下类似地指示编译器,让它知道a.ipb.ip不会重叠?

2个回答

17

您还可以在结构体内使用restrict

struct s {
    /* ... */
    int * restrict ip;
};

int f2(struct s a, struct s b)
{
    /* ... */
}

因此,编译器可以假定在每次调用 f2 函数期间,a.ipb.ip 用于引用不相交的对象。


-2
检查这个指针示例,你可能会得到一些帮助。
// xa and xb pointers cannot overlap ie. point to same memmpry location.
void function (restrict int *xa, restrict int *xb)
{
    int temp = *xa;
    *xa = *xb;
    xb = temp;
}

如果两个指针被声明为restrict,则这两个指针不重叠。 编辑

查看此链接以获取更多示例


1
我不明白这如何回答问题 - 原帖作者显然知道如何使用普通指针来完成它,代码已经在问题中了。 - Mat
1
也许编写一个针对 a.ip 和 b.ip 类型的函数而非 a 和 b 本身会是一个好的解决方案。这取决于结构体的性质,如果 a 和 b 是 OO 设计中使用的不完整类型,则该方法无法奏效。 - Lundin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接