Is the data in nested std::arrays guaranteed to be contiguous?

后端 未结 2 1465
面向向阳花
面向向阳花 2020-11-29 09:30

Is the data in std::array, M> guaranteed to be contiguous? For example:

#include 
#include 

        
相关标签:
2条回答
  • 2020-11-29 09:51

    They are very likely contiguous. If they are not, the compiler is actively fighting you there. There's no guarantee it won't insert padding but there's hardly a reason for it.

    Is the assert guaranteed to succeed?

    data[7] is an out-of-bounds access (undefined behaviour). The inner array object has only seven elements, so index 7 is not valid.

    0 讨论(0)
  • 2020-11-29 10:01

    No, contiguity is not guaranteed in this case.

    std::array is guaranteed to be an aggregate, and is specified in such a way that the underlying array used for storage must be the first data member of the type.

    However, there is no requirement that sizeof(array<T, N>) == sizeof(T) * N, nor is there any requirement that there are no unnamed padding bytes at the end of the object or that std::array has no data members other than the underlying array storage. (Though, an implementation that included additional data members would be, at best, unusual.)

    0 讨论(0)
提交回复
热议问题