Is std::memcpy between different trivially copyable types undefined behavior?

前端 未结 3 2047
闹比i
闹比i 2020-12-24 10:52

I\'ve been using std::memcpy to circumvent strict aliasing for a long time.

For example, inspecting a float, like this:

         


        
3条回答
  •  青春惊慌失措
    2020-12-24 11:18

    Your example is well-defined and does not break strict aliasing. std::memcpy clearly states:

    Copies count bytes from the object pointed to by src to the object pointed to by dest. Both objects are reinterpreted as arrays of unsigned char.

    The standard allows aliasing any type through a (signed/unsigned) char* or std::byte and thus your example doesn't exhibit UB. If the resulting integer is of any value is another question though.


    use i to extract f's sign, exponent & significand

    This however, is not guaranteed by the standard as the value of a float is implementation-defined (in the case of IEEE 754 it will work though).

提交回复
热议问题