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

Quick A: Yes, you can copy bitwisely from one to the other.

Recently on SO:

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

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).

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.