假设我有一个函数,它接受一些指针参数 - 一些非常量,可以通过它们写入,一些常量,只能通过它们读取。示例:
void f(int * a, int const *b);
还假设该函数不会以其他方式写入内存(即不使用全局变量,固定地址,将 const 指针重铸为非常量以及诸如此类的技巧)。
现在,是否足以(按照 C 语言标准)实现restrict
内所有读取的好处f()
,而仅restrict
输出参数?即在示例中,限制a
但不限制b
?
一个简单的测试(GodBolt)表明这种限制应该足够了。此来源:
int f(int * restrict a, int const * b) {
a[0] += b[0];
return a[0] + b[0];
}
int all_restricted(int * restrict a, int const * restrict b) {
a[0] += b[0];
return a[0] + b[0];
}
int unrestricted(int * a, int const * b) {
a[0] += b[0];
return a[0] + b[0];
}
为 x86_64 生成相同的目标代码:
f:
mov eax, DWORD PTR [rsi]
mov edx, DWORD PTR [rdi]
add edx, eax
mov DWORD PTR [rdi], edx
add eax, edx
ret
all_restricted:
mov eax, DWORD PTR [rsi]
mov edx, DWORD PTR [rdi]
add edx, eax
mov DWORD PTR [rdi], edx
add eax, edx
ret
unrestricted:
mov eax, DWORD PTR [rsi]
add eax, DWORD PTR [rdi]
mov DWORD PTR [rdi], eax
add eax, DWORD PTR [rsi]
ret
但这并非普遍的保证。