代码之家  ›  专栏  ›  技术社区  ›  A. K.

当指针是__restrict类型时,编译器从std::copy生成对memcpy的调用?

  •  0
  • A. K.  · 技术社区  · 3 年前

    gcc编译器生成调用 memcpy 当我添加 __restrict 函数参数。 编译器/标准库如何确定它可以生成对以下对象的调用 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

    如果源和目标范围重叠,则行为未定义。

    原则上,编译器不应该生成对 memcpy 总是?

    连接到螺栓: https://godbolt.org/z/aKj3Y5K8M

    1 回复  |  直到 3 年前
        1
  •  3
  •   user17732522    3 年前

    您的报价适用于 std::copy_if ,不是为了 std::copy .

    唯一的要求是 std::copy 是吗 q 不在范围内 [p,p+sz) 目的地范围允许重叠,因此 memmove 是唯一没有额外假设的选择,例如 __restrict .

    __限制 向编译器保证范围不会重叠。