While there might be an XY issue that led me here, I am curious about the limits of the new bit_cast
in C++20, and this seems a good illustration of it.
Note that there is nothing inherently wrong with std::memcpy
and it does not cause undefined behavior. It is also enough of an idiom to generally be optimized out to be the equivalent of a cast. The problem I have is that the intent of its usage is not as clear as it could be and it seems more C than C++.
How could you use bit_cast
to do the same thing (without any undefined behavior) as the following:
#include <cstring>
void ptr2array(short (&x)[], int offset, const void * ptr)
{
std::memcpy(&(x[offset]), ptr, sizeof(void *));
}
void array2ptr(void * & ptr, int offset, short (&x)[])
{
std::memcpy(ptr, &(x[offset]), sizeof(void *));
}
Note that the following is fundamentally a no-op (tested here: https://godbolt.org/z/ce9Ecx8TG)
void * tst(void * orig)
{
short x[101];
int offset = 67;
void * ret=orig;
ptr2array(x, offset, ret);
array2ptr(ret, offset, x);
return ret;
}
Keep in mind that memcpy works fine with the misalignment (using offset).
Also requiring an array of shorts, as opposed to char, avoids some of the leniencies with char, but keeps the alignment issues.