虽然该行为确实是明确定义的 - 但它是not确实,编译器可以按照您的意思“优化 const”。
也就是说,编译器是not允许假设仅仅因为参数是const T* ptr
,指向的内存ptr
不会通过另一个指针改变。指针甚至不必相等。这const
是一项义务,而不是保证 - 您(= 函数)有义务不通过该指针进行更改。
为了真正得到这个保证,你需要用restrict
关键词。因此,如果编译这两个函数:
int foo(const int* x, int* y) {
int result = *x;
(*y)++;
return result + *x;
}
int bar(const int* x, int* restrict y) {
int result = *x;
(*y)++;
return result + *x;
}
the foo()
函数必须读取两次x
, while bar()
只需要读一次:
foo:
mov eax, DWORD PTR [rdi]
add DWORD PTR [rsi], 1
add eax, DWORD PTR [rdi] # second read
ret
bar:
mov eax, DWORD PTR [rdi]
add DWORD PTR [rsi], 1
add eax, eax # no second read
ret
See this live on GodBolt https://godbolt.org/z/NnG9dP.
restrict
仅是 C 中的一个关键字(自 C99 起);不幸的是,到目前为止它还没有被引入到C++中(可怜的原因是在C++中引入它比较复杂)。然而,许多编译器确实支持它,因为__restrict
.
底线:编译器在编译时必须支持您的“深奥”用例f()
,并且不会有任何问题。
See this post https://stackoverflow.com/q/745870/1593077 regarding use cases for restrict
.