是否保证嵌套std ::数据中的数据是连续的? [英] Is the data in nested std::arrays guaranteed to be contiguous?

查看:216
本文介绍了是否保证嵌套std ::数据中的数据是连续的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据是否在 std :: array< std :: array< T,N>,M> 例如:

  #include< array> 
#include< cassert>

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

/ * 1D数据数组的第8个元素应与第二行的
第1个元素相同。 * /
assert(data [7] == 42);
}

断言是否成功?或者换句话说,我可以依靠 Row



结尾处没有填充> EDIT:为了清楚起见,在本例中,我希望整个矩阵的数据是连续的。



std :: array

code>保证是一个聚合,并且以这样一种方式指定,用于存储的底层数组必须是类型的第一个数据成员。



然而,不需要 sizeof(array )== sizeof(T)* N ,也没有要求没有未命名的填充字节或者 std :: array 除了底层数组存储之外没有数据成员。 (但是,包含其他数据成员的实现最多只是不寻常的。)


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);
}

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?

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

这篇关于是否保证嵌套std ::数据中的数据是连续的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆