c++ - 缓冲区填充不同类型的数据,并严格别名

标签 c++ c++11 c++14 strict-aliasing

根据 the standard ,在 C++ 中总是未定义的行为,例如,使 float* 指向与 int* 相同的内存位置,然后从它们读取/写入。

在我的应用程序中,可以有一个缓冲区,其中填充了 32 位整数元素,这些元素被 32 位浮点元素覆盖。 (它实际上包含图像的表示,由 GPU 内核在多个阶段进行转换,但也应该有一个执行相同处理的主机实现,以进行验证。)

程序基本上是这样做的(不是实际的源代码):

void* buffer = allocate_buffer(); // properly aligned buffer

static_assert(sizeof(std::int32_t) == sizeof(float), "must have same size");
const std::int32_t* in = reinterpret_cast<const std::int32_t*>(buffer); 
float* out = reinterpret_cast<float*>(buffer); 
for(int i = 0; i < num_items; ++i)
   out[i] = transform(in[i]);

有没有办法在 C++ 标准中明确定义 reinterpret_cast 指针情况,而无需对整个缓冲区进行额外的内存复制,或额外的每个元素复制(例如使用 std::bit_cast)?

最佳答案

尽管我一直希望有一个好的方法,但目前还没有。您将必须使用您选择的编译器的 no-strict-aliasing 标志。

对于 std::bit_cast,您必须等到 C++20。据我所知,不使用 memcpy 就没有符合标准的方法。

也看看这个 bit_cast proposalthis website .

关于c++ - 缓冲区填充不同类型的数据,并严格别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51930334/

相关文章:

c++ - 变量模板编译时数组

c++ - 如何检查模板类型参数是字符类型还是字符串类型?

c++ - QVideoWidget 独立。窗口关闭时如何停止视频?

c++ - 放置-新地址对齐

c++ - 为什么复制到的对象必须与复制自的对象具有相同的低级别常量?

c++ - 使用 std::shared_ptr 分配类成员

c++ - 是否可以直接访问 multimap 中的位置(不是键)

c++ - 为什么我不能用 reset() 删除 unique_ptr<char[]>?

c++ - 重载运算符体只包含一个函数调用

c++ - 线程池 : Block destruction until all work is done