std::copy 关于指向易失性数据的指针

std::copy on pointers to volatile data

假设我有一个指向易失性数据的输入和输出指针.....我尝试对它们使用 std::copy:

uint32_t volatile* input = /*    */;
uint32_t volatile* output =  /*    */;
std::copy(input,input+512,output);

这应该编译吗?我的想法是它应该,但是它在 gcc 上失败了,因为它试图使用 __builtin_memmove,这需要指向非易失性数据的指针......link 到 godbolt:https://godbolt.org/z/6yDzqb

所以我想我的问题是:这是标准库中的错误还是允许编译失败?

是的,这应该编译。 std::copy 指定为 [alg.copy]/2 to behave as if the value obtained from dereferencing the iterator to each element in the source range was simply assigned to the value obtained from dereferencing the iterator to the corresponding element in the destination range. A volatile std::uint32_t can be assigned to a volatile std::uint32_t because a volatile std::uint32_t is not const [basic.lval]/7.

另外,请注意这个 does apparently compile 在 GCC 的主干版本上(至少在 godbolt 上可用)。所以我想说这几乎可以肯定是一个错误,现在似乎已经修复了……

除此之外,您可能需要考虑包含 <cstdint> 而不是 <stdint.h>,因为 C 标准库 headers 仅在 C++ 中作为已弃用的兼容性功能提供 [depr.c.headers]. When you do, be aware of the fact that it is unspecified [requirements.headers]/4 这些标准 headers 中声明的实体,例如 std::uint32_t 是否在全局命名空间中实际可用。因此,您可能要考虑使用 std::uint32_t 而不仅仅是 uint32_t 等,因为实际上只有前者可以保证存在……