restrict
Microsoft 特定的
當套用至傳回指標類型的函式宣告或定義時, restrict
告訴編譯器函式傳回不是 別名 的物件,也就是任何其他指標所參考的物件。 這可讓編譯器執行其他優化。
語法
__declspec(restrict)
pointer_return_type 函 式():
備註
編譯器會 __declspec(restrict)
傳播 。 例如,CRT malloc
函式具有 __declspec(restrict)
裝飾,因此,編譯器會假設由 初始化至記憶體位置 malloc
的指標也不是先前現有指標的別名。
編譯器不會檢查傳回的指標是否實際上沒有別名。 開發人員有責任確保程式不會將標示 為限制__declspec 修飾詞的指標加上別名。
如需變數上的類似語意,請參閱 __restrict 。
如需適用于函式內別名的另一個批註,請參閱 __declspec(noalias) 。
如需屬於 C++ AMP 之關鍵字的資訊 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);
}
END Microsoft 特定的
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應