Get a value of non-default-constructible type `T` from a byte array without undefined behavior

1 day ago 1
ARTICLE AD BOX

I'm messing with FFI between Rust and C++ and I happen to know that some particular array of bytes pointed by a std::byte * pointer is a valid C++ object of type T, which can be anything for what concerns this question.

How do I get back a valid value of type T from this array of bytes?

What does not work:

reinterpret_cast does not work because of the strict aliasing rules, apparently:

template<typename T> T transmute(std::byte *ptr) { return *reinterpret_cast<T *>(ptr); // UB }

memcpy works but requires T to be default constructible.

template<typename T> T transmute(std::byte *ptr) { T value; // requires a default constructor memcpy(&value, ptr, sizeof(T)); return value; }

the latter is usually suggested (also on the cppreference page on reinterpret_cast ), but I cannot assume T to be default-constructible.

Unions are useless because reading from the non-active member is UB:

template<typename T> T transmute(std::byte *ptr) { union { T value; std::byte bytes[sizeof(T)]; } thing; memcpy(&thing.bytes, ptr, sizeof(T)); return thing.value; // UB }

So is there a way to do that for an arbitrary T without undefined behavior?

Read Entire Article