3 ms·
This comment isn't meant to disagree with what you said but is more like a related ramble. At least in C++, memcpy is special because it can be used to reinter
by quietbritishjim 5y ago
This comment isn't meant to disagree with what you said but is more like a related ramble.
At least in C++, memcpy is special because it can be used to reinterpret bits of one object as another (in C you can use a union, and as of C++20 you can use the std::bit_cast function but it either just calls memcpy or it still needs its own magic)
double d = 1.0;
// type punning with union, allowed in C but not C++
union {
double d;
int64_t i;
} u;
u.d = d;
int64_t y1 = u.i; // undefined behaviour
// cast not allowed, not even reinterpret_cast
int64_t y2 = *reinterpret_cast<int64_t*>(&x.d); // undefined behaviour
// memcpy - allowed! (if sizeof() params is the same)
int64_t y3;
static_assert(sizeof(y3) == sizeof(d));
memcpy(&y3, &d, sizeof(y3)); // well defined!
// C++20 bit_cast (probably just a convenience wrapper around memcpy)
int64_t y4 = std::bit_cast<int64_t>(d); // well defined
It seems wasteful to create a separate object in memory and copy bits from an old object, when all you want to do is reinterpret the bits of the existing chunk of memory. But memcpy doesn't do that (or at least might not) because it's optimised into a simple cast under the hood, but without the undefined behaviour. So memcpy looks like a standard library function but in a way it's more like a compiler instrinic. It would be possible to create a fully conformant version of memcpy, even in C++, by casting both parameters to char* which is special with respect to the aliasing rules, and copying char-by-char. But I suppose that would be harder to optimise into a simple cast.
- matheusmoreira 5y agoWhat a pain, right? Why can't they just let us do what they know we want to do? It's such an absurd situation. We have double precision floating point numbers. Sometimes we want to look at the bits. Sometimes we want to modify those bits. Would it kill them to let us cast the thing? I will never understand this.