Is the underlying bit representation for an std::array<T,N> v
and a T u[N]
the same?
In other words, is it safe to copy N*sizeof(T)
bytes from one to the other? (Either through reinterpret_cast
or memcpy
.)
Edit:
For clarification, the emphasis is on same bit representation and reinterpret_cast
.
For example, let's suppose I have these two classes over some trivially copyable type T
, for some N
:
struct VecNew { std::array<T,N> v; }; struct VecOld { T v[N]; };
And there is the legacy function
T foo(const VecOld& x);
If the representations are the same, then this call is safe and avoids copying:
VecNew x; foo(reinterpret_cast<const VecOld&>(x));
std::array has value semantics while raw arrays do not. This means you can copy std::array and treat it like a primitive value. You can receive them by value or reference as function arguments and you can return them by value. If you never copy a std::array , then there is no performance difference than a raw array.
std::array is a container that encapsulates fixed size arrays. This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member. Unlike a C-style array, it doesn't decay to T* automatically.
std::array provides many benefits over built-in arrays, such as preventing automatic decay into a pointer, maintaining the array size, providing bounds checking, and allowing the use of C++ container operations. As mentioned above, std::array is a templated class that represents fixed-size arrays.
This doesn't directly answer your question, but you should simply use std::copy
:
T c[N]; std::array<T, N> cpp; // from C to C++ std::copy(std::begin(c), std::end(c), std::begin(cpp)); // from C++ to C std::copy(std::begin(cpp), std::end(cpp), std::begin(c));
If T
is a trivially copyable type, this'll compile down to memcpy
. If it's not, then this'll do element-wise copy assignment and be correct. Either way, this does the Right Thing and is quite readable. No manual byte arithmetic necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With