嵌套的 std::arrays 中的数据是否保证是连续的?

2021-12-21 00:00:00 multidimensional-array c++ c++11

std::array, M> 中的数据是否保证连续?例如:

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

#include <array>
#include <cassert>

int main()
{
    enum {M=4, N=7};
    typedef std::array<char,N> Row;
    typedef std::array<Row, M> Matrix;
    Matrix a;
    a[1][0] = 42;
    const char* data = a[0].data();

    /* 8th element of 1D data array should be the same as
       1st element of second row. */
    assert(data[7] == 42);
}

断言是否保证成功?或者,换句话说,我可以依靠 Row 的末尾没有填充吗?

Is the assert guaranteed to succeed? Or, to put it another way, can I rely on there being no padding at the end of a Row?

为了清楚起见,对于这个例子,我希望整个矩阵的数据是连续的.

Just to be clear, for this example, I want the data of the entire matrix to be contiguous.

推荐答案

不,在这种情况下不保证连续性.

No, contiguity is not guaranteed in this case.

std::array 保证是一个聚合,并以这样一种方式指定,即用于存储的底层数组必须是该类型的第一个数据成员.

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.

但是,没有要求sizeof(array) == sizeof(T) * N,也没有要求最后没有未命名的填充字节对象或 std::array 除了底层数组存储之外没有数据成员.(不过,包含额外数据成员的实现充其量是不寻常的.)

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.)

相关文章