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

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

    This doesn't directly answer your question, but you should simply use std::copy:

    T c[N];
    std::array 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.

提交回复
热议问题