std::bit_cast with std::array

前端 未结 3 1870
孤独总比滥情好
孤独总比滥情好 2021-02-19 09:29

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]

3条回答
  •  礼貌的吻别
    2021-02-19 10:04

    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::value);
    
        Dest dest;
        std::memcpy(&dest, &source, sizeof(dest));
        return dest;
    }
    

    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.

提交回复
热议问题