缓冲区中填充了不同类型的数据,并严格混叠 [英] Buffer filled with different types of data, and strict aliasing
问题描述
根据标准,它始终是未定义的行为例如,使用C ++将 float *
指向与 int *
相同的内存位置,然后读取
According to the standard, it is always undefined behavior in C++ to make, for example, a float*
point to the same memory location as a int*
, and then read/write from them.
在我拥有的应用程序中,可以有一个填充有32位整数元素的缓冲区,该缓冲区被32位浮点元素覆盖。 (它实际上包含一张图像的表示,该图像通过GPU内核在多个阶段中进行了转换,但是还应该有一个主机执行该过程,以进行验证)。
In the application I have, there can be a buffer filled with 32-bit integer elements, that are overwritten by 32-bit floating point elements. (It actually contains a representation of an image, that gets transformed in multiple stages by GPU kernels, but there should also be a host implementation that does the same processing, for verification.)
程序基本上是这样做的(不是实际的源代码):
The program basically does this (not actual source code):
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]);
有没有办法使 reinterpret_cast
指针情况在C ++标准中定义良好,而不需要对整个缓冲区进行额外的内存复制,也不进行额外的按元素复制(例如,使用 std :: bit_cast
)?
Is there a way to make the reinterpret_cast
pointer cases well-defined, within the C++ standard, without doing additional memory copies of the whole buffer, or additional per-element copies (for example with std::bit_cast
)?
推荐答案
即使我一直希望有一种不错的方法,但目前还没有。您必须使用所选编译器的 no-strict-aliasing
标志。
Even though I wished all the time there would be a nice way, currently there is non. You will have to use no-strict-aliasing
flag of the compiler of your choice.
对于 std :: bit_cast
,您将不得不等到 C ++ 20
。据我所知,没有使用 memcpy
就是没有标准的遵循方式。
For std::bit_cast
you will have to wait until C++20
. There is no standard conform way without using memcpy
as far as I know.
也可以看看< a href = http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0476r1.html rel = nofollow noreferrer> bit_cast提案和此网站。
这篇关于缓冲区中填充了不同类型的数据,并严格混叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!