Is the std::array bit compatible with the old C array?

后端 未结 5 1840
心在旅途
心在旅途 2020-12-30 21:24

Is the underlying bit representation for an std::array v and a T u[N] the same?

In other words, is it safe to copy

5条回答
  •  旧巷少年郎
    2020-12-30 21:26

    The requirement on the data() method is that it return a pointer T* such that:

    [data(), data() + size()) is a valid range, and data() == addressof(front()).

    This implies that you can access each element sequentially via the data() pointer, and so if T is trivially copyable you can indeed use memcpy to copy sizeof(T) * size() bytes to/from an array T[size()], since this is equivalent to memcpying each element individually.

    However, you cannot use reinterpret_cast, since that would violate strict aliasing, as data() is not required to actually be backed by an array - and also, even if you were to guarantee that std::array contains an array, since C++17 you cannot (even using reinterpret_cast) cast a pointer to an array to/from a pointer to its first member (you have to use std::launder).

提交回复
热议问题