In his recent talk “Type punning in modern C++” Timur Doumler said that std::bit_cast
cannot be used to bit cast a float
into an unsigned char[4]
Yes.
According to the paper that describes the behaviour of std::bit_cast
, and its proposed implementation as far as both types have the same size and are trivially copyable the cast should be successful.
A simplified implementation of std::bit_cast
should be something like:
template
inline Dest bit_cast(Source const &source) {
static_assert(sizeof(Dest) == sizeof(Source));
static_assert(std::is_trivially_copyable::value);
static_assert(std::is_trivially_copyable
Since a float (4 bytes) and an array of unsigned char
with size_of(float)
respect all those asserts, the underlying std::memcpy
will be carried out. Therefore, each element in the resulting array will be one consecutive byte of the float.
In order to prove this behaviour, I wrote a small example in Compiler Explorer that you can try here: https://godbolt.org/z/4G21zS. The float 5.0 is properly stored as an array of bytes (Ox40a00000
) that corresponds to the hexadecimal representation of that float number in Big Endian.