restrict
Microsoft 专用
当应用于返回指针类型的函数声明或定义时,restrict
通知编译器该函数将返回没有别名(即被任何其他指针引用)的对象。 这允许编译器执行其他优化。
语法
__declspec(restrict)
pointer_return_typefunction();
备注
编译器传播 __declspec(restrict)
。 例如,CRT malloc
函数具有 __declspec(restrict)
修饰,因此,编译器假定由 malloc
初始化到内存位置的指针也不会被之前存在的指针指定别名。
编译器不检查指针到底有没有使用别名。 开发人员负责确保程序没有对使用 restrict __declspec 修饰符标记的指针使用别名。
有关变量的类似语义,请参阅 __restrict。
有关应用于函数内别名的另一个注释,请参阅 __declspec(noalias)。
有关作为 C++ AMP 的一部分的 restrict
关键字的信息,请参阅 restrict (C++ AMP)。
示例
以下示例演示了 __declspec(restrict)
的用法。
当 __declspec(restrict)
应用于返回指针的函数时,这会告知编译器返回值指向的内存没有别名。 在此示例中,指针 mempool
和 memptr
为全局指针,因此编译器无法确定所引用的内存没有别名。 但是,它们以返回程序未引用的内存的方式在 ma
及其调用方 init
内部使用,因此,__decslpec(restrict) 用于帮助优化器。 这类似于 CRT 标头如何修饰分配函数,例如 malloc
,方法是使用 __declspec(restrict)
指示它们始终返回无法由现有指针别名的内存。
// declspec_restrict.c
// Compile with: cl /W4 declspec_restrict.c
#include <stdio.h>
#include <stdlib.h>
#define M 800
#define N 600
#define P 700
float * mempool, * memptr;
__declspec(restrict) float * ma(int size)
{
float * retval;
retval = memptr;
memptr += size;
return retval;
}
__declspec(restrict) float * init(int m, int n)
{
float * a;
int i, j;
int k=1;
a = ma(m * n);
if (!a) exit(1);
for (i=0; i<m; i++)
for (j=0; j<n; j++)
a[i*n+j] = 0.1f/k++;
return a;
}
void multiply(float * a, float * b, float * c)
{
int i, j, k;
for (j=0; j<P; j++)
for (i=0; i<M; i++)
for (k=0; k<N; k++)
c[i * P + j] =
a[i * N + k] *
b[k * P + j];
}
int main()
{
float * a, * b, * c;
mempool = (float *) malloc(sizeof(float) * (M*N + N*P + M*P));
if (!mempool)
{
puts("ERROR: Malloc returned null");
exit(1);
}
memptr = mempool;
a = init(M, N);
b = init(N, P);
c = init(M, P);
multiply(a, b, c);
}
结束 Microsoft 专用
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈