在他的论文中,内存优化 https://web.archive.org/web/20160422113037/http://www.research.scea.com/research/pdfs/GDC2003_Memory_Optimization_18Mar03.pdf,克里斯特·埃里克森说,虽然restrict
尚未成为 C++ 标准的一部分,许多编译器都支持它,他建议在可用时使用它:
限制关键字
! 1999 年 ANSI/ISO C 标准的新增内容
!尚未纳入 C++ 标准,但许多 C++ 编译器都支持
!仅作为提示,因此可能什么都不做但仍然符合要求
限制限定指针(或引用)...
! ...基本上是一个
向编译器承诺
指针的作用域,指针的目标只会
通过该指针访问(并且复制的指针
从中)。
在支持它的 C++ 编译器中,它的行为可能与 C 中的行为相同。
有关详细信息,请参阅此 SO 帖子:C99“restrict”关键字的实际用法? https://stackoverflow.com/questions/745870/realistic-usage-of-the-c99-restrict-keyword
花半个小时浏览一下Ericson的论文,很有趣,值得花时间。
Edit
我还发现IBM的AIX C/C++ 编译器支持__restrict__ keyword http://www-01.ibm.com/support/knowledgecenter/SSLTBW_2.1.0/com.ibm.zos.v2r1.cbclx01/restrict_type_qualifier.htm?lang=en.
g++ 似乎也支持这一点,因为以下程序可以在 g++ 上干净地编译:
#include <stdio.h>
int foo(int * __restrict__ a, int * __restrict__ b) {
return *a + *b;
}
int main(void) {
int a = 1, b = 1, c;
c = foo(&a, &b);
printf("c == %d\n", c);
return 0;
}
我还发现了一篇关于使用的好文章restrict
:
揭秘 Restrict 关键字 http://cellperformance.beyond3d.com/articles/2006/05/demystifying-the-restrict-keyword.html
Edit2
我读过一篇文章,专门讨论了 C++ 程序中限制的使用:
Load-hit-stores 和 __restrict 关键字 http://assemblyrequired.crashworks.org/load-hit-stores-and-the-__restrict-keyword/
另外,微软 Visual C++还支持__restrict keyword http://msdn.microsoft.com/en-us/library/5ft82fed(VS.80).aspx.