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 pointerT*
such that:[data(), data() + size())
is a valid range, anddata() == addressof(front())
.This implies that you can access each element sequentially via the
data()
pointer, and so ifT
is trivially copyable you can indeed usememcpy
to copysizeof(T) * size()
bytes to/from an arrayT[size()]
, since this is equivalent tomemcpy
ing each element individually.However, you cannot use
reinterpret_cast
, since that would violate strict aliasing, asdata()
is not required to actually be backed by an array - and also, even if you were to guarantee thatstd::array
contains an array, since C++17 you cannot (even usingreinterpret_cast
) cast a pointer to an array to/from a pointer to its first member (you have to usestd::launder
).
Add a Comment
Comments are closed.