I was reading this excellent material about the strict aliasing rule: https://stackoverflow.com/a/51228315/21691539 or https://gist.github.com/shafik/a956a17d00024b32b35634eeba1eb49e
But in the section about std::bit_cast and an alleged limitation of std::bit_cast, I don't understand the need for both a std::memcpy and a std::bit_cast.
The provided example seemed a bit contrived and can be simplified to:
#include
#include
struct some_chars {
unsigned char arr[sizeof(unsigned int)] = {};
};
unsigned int foo(unsigned char *p) {
some_chars a;
std::memcpy(a.arr, p, sizeof(unsigned int));
unsigned int result = std::bit_cast(a);
return result;
}
(see here)
(Here and in the following, p is assumed to point to a storage of at least sizeof(unsigned int) unsigned char)
I'm finding the purpose of the intermediate struct unclear. What would be wrong with the following?
unsigned int foo(unsigned char *p) {
unsigned int result;
std::memcpy(&result, p, sizeof(unsigned int));
return result;
}
why not std::memcpy directly into an unsigned int as illustrated in cpprefence?
// reinterpreting
double d = 0.1;
// std::int64_t n = *reinterpret_cast(&d); // aliasing violation
std::int64_t n;
std::memcpy(&n, &d, sizeof d); // OK