当指针为 __restrict 类型时,编译器会从 std::copy 生成对 memcpy 的调用?
当我将 __restrict 添加到函数参数时,gcc 编译器会生成对 memcpy 的调用。 编译器/标准库如何确定它可以在适当的时候生成对 memcpy 的调用?
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
}
根据 https://en.cppreference.com/w/cpp/algorithm/copy< /a>
如果源范围和目标范围重叠,则行为未定义。
原则上,编译器不应该始终生成对 memcpy 的调用吗?
链接到 godbolt:https://godbolt.org/z/aKj3Y5K8M
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的报价适用于
std::copy_if
,而不是std::copy
。std::copy
的唯一要求是q
不在[p,p+sz)
范围内。目标范围允许重叠,因此memmove
是唯一没有额外假设的选项,例如由__restrict
引入的。__restrict
向编译器保证范围不会重叠。Your quote applies to
std::copy_if
, not tostd::copy
.The only requirement for
std::copy
is thatq
is not in the range[p,p+sz)
. The destination range is allowed to overlap and thereforememmove
is the only option without additional assumptions, such as introduced by__restrict
.__restrict
guarantees the compiler that the ranges will not overlap.