Microsoft 特定的
當套用至會傳回指標類型的函式宣告或定義時,restrict
會告知編譯器該函式會傳回物件,該物件不具有任何其他指標所參考的別名。 這可讓編譯器執行其他最佳化。
語法
__declspec(restrict)
pointer_return_type function();
備註
編譯器會傳播 __declspec(restrict)
。 例如,CRT malloc
函式具有 __declspec(restrict)
裝飾,因此,此編譯器會假設由 malloc
初始化至記憶體位置的指標也不具有先前現有指標的別名。
此編譯器不會檢查傳回的指標實際上有沒有別名。 開發人員必須負責確保程式不會對以 restrict __declspec 修飾元標記的指標使用別名。
如需變數的類似語法,請參閱 __restrict。
如需適用於函式內別名的另一個註釋,請參閱 __declspec(noalias)。
如需有關屬於 C++ AMP 之 restrict
關鍵字的詳細資訊,請參閱限制 (C++ AMP)。
範例
以下範例示範如何使用 __declspec(restrict)
。
將 __declspec(restrict)
套用至會傳回指標的函式,可讓編譯器知道傳回值所指向的記憶體沒有別名。 在此範例中,mempool
和 memptr
是全域的指標,因此此編譯器無法確定其所參考的記憶體是否沒有別名。 不過,會以傳回程式未參考之記憶體的方式,在 ma
及其呼叫端 init
中使用這些指標,因此會使用 __decslpec(restrict) 來協助最佳化工具。 這類似於 CRT 標頭透過使用 __declspec(restrict)
裝飾 malloc
之類配置函式的方式,來表示其一律會傳回現有指標無法設為別名的記憶體。
// 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);
}
END Microsoft 特定的