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

后端 未结 5 1847
心在旅途
心在旅途 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:27

    std::array provides method data() which can be used to copy to/from c-style array of proper size:

    const size_t size = 123;
    int carray[size];
    std::array array;
    
    memcpy( carray, array.data(), sizeof(int) * size );
    memcpy( array.data(), carray, sizeof(int) * size );
    

    As stated on documentation

    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.

    so it seems that memory footprint would be compatible with c-style array, though it is not clear why you want to use "hacks" with reinterpret_cast when there is a proper way which does not have any overhead.

提交回复
热议问题