Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)); 
like image 269
shinjin Avatar asked Sep 07 '16 18:09

shinjin


People also ask

What is the difference between std :: array and array?

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.

Is std :: array fixed size?

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.

Is std :: array useful?

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.


1 Answers

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.

like image 55
Barry Avatar answered Sep 20 '22 04:09

Barry