std::bit_cast with std::array

前端 未结 3 1874
孤独总比滥情好
孤独总比滥情好 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 09:58

    The accepted answer is incorrect because it fails to consider alignment and padding issues.

    Per [array]/1-3:

    The header defines a class template for storing fixed-size sequences of objects. An array is a contiguous container. An instance of array stores N elements of type T, so that size() == N is an invariant.

    An array is an aggregate that can be list-initialized with up to N elements whose types are convertible to T.

    An array meets all of the requirements of a container and of a reversible container ([container.requirements]), except that a default constructed array object is not empty and that swap does not have constant complexity. An array meets some of the requirements of a sequence container. Descriptions are provided here only for operations on array that are not described in one of these tables and for operations where there is additional semantic information.

    The standard does not actually require std::array to have exactly one public data member of type T[N], so in theory it is possible that sizeof(To) != sizeof(From) or is_­trivially_­copyable_­v.

    I will be surprised if this doesn't work in practice, though.

提交回复
热议问题