I have a class whose purpose is to move data which might have alignment restrictions to or from a serialized memory buffer where the data is not aligned. I have set and get handlers as follows:
#include <cstring>
template<typename T>
struct handle_type {
static inline T get(const void *data) {
T value;
memcpy(&value, data, sizeof(T));
return value;
}
static inline void set(void *data, T value) {
memcpy(data, &value, sizeof(T));
}
};
After c++20 comes out, I am hoping it will become something like the following:
#include <bit>
template<typename T>
struct handle_type {
union unaligned { char bytes[sizeof(T)]; }; // EDIT: changed from struct
static inline T get(const void *data) {
return std::bit_cast<T>(*(const unaligned*)data);
}
static inline void set(void *data, T value) {
*(unaligned *)data = std::bit_cast<unaligned>(value);
}
};
Will it work? Or is the fact that I am using an inerim type, the unaligned struct type, liable to pose a problem?