The gcc compiler generates call to memcpy
when i add __restrict
to function parameters.
How does compiler/standard library figure out that it can generate calls to memcpy
when appropriate?
void call_stdcpy_r(int *__restrict p, int *__restrict q, int sz) {
std::copy(p, p sz, q); // generates call to memcpy
}
void call_stdcpy(int *p, int *q, int sz) {
std::copy(p, p sz, q); // generates call to memmove
}
As per https://en.cppreference.com/w/cpp/algorithm/copy
The behavior is undefined if the source and the destination ranges overlap.
Shouldn't the compiler, in principle, generate calls to memcpy
all the time?
Link to godbolt: https://godbolt.org/z/aKj3Y5K8M
CodePudding user response:
Your quote applies to std::copy_if
, not to std::copy
.
The only requirement for std::copy
is that q
is not in the range [p,p sz)
. The destination range is allowed to overlap and therefore memmove
is the only option without additional assumptions, such as introduced by __restrict
.
__restrict
guarantees the compiler that the ranges will not overlap.