std::vector<std::array<T, N>> 或 std::array<std::vector<T>,N> 类型的数组如何存储在内存中?

How are arrays of type std::vector<std::array<T, N>> or std::array<std::vector<T>,N> stored in memory?

我知道std::vector<T>在堆上分配动态内存。我也知道 std::array<T,N> 在堆栈上分配内存。

但是当我将两个容器合并在一起时,内存是如何分配的?

喜欢f.e.:

std::vector<std::array<T, N>> a;

std::array<std::vector<T>,N> a;

作者:

std::vector<std::array<T, N>> a;

作者:

std::array<std::vector<T>,N> a;

非常感谢您的参与。

基本上,std::array<T, N>T 对象存储在对象本身 中,就像它们是普通数据成员一样,而 std::vector<T> 在堆上分配缓冲区并在该内存 上构造T 对象。

当谈到std::array<T, N>时,由于T对象在std::array本身内部,这些T对象是否分配在取决于std::array<T, N>的分配位置:

  • 如果 std::array<T, N> 分配在堆栈上,那么 T 对象也会分配。

  • 如果 std::array<T, N> 分配在堆上(例如,new std::array<T, N>),T 对象也会分配。


std::vector<std::array<T, N>>

向量将所有 std::array<T, N> 对象存储在其内部缓冲区中,该缓冲区分配在堆上。即假设vec_of_arrs自动存储时长:

std::vector<std::array<T, N>> vec_of_arrs;

只有对象vec_of_arrs被分配到栈上。它的内部缓冲区——在堆上创建连续的 std::array<T, N> 对象序列。由于 T 对象直接存储在 std::array 中,它们也在该内存(即堆)上构建。


std::array<std::vector<T>,N>

std::arraystd::vector<T> 类型的 N 对象直接存储为自身的数据成员。因此,如果包含 std::vector<T> 对象的 std::array 被分配到堆栈上,那么它们将在堆栈上。但是,每个向量的 内部缓冲区 都分配在堆上, T 对象也是如此,因为它们是在该缓冲区上构建的。即假设arr_of_vecs自动存储时长:

std::array<std::vector<T>,N> arr_of_vecs;

对象arr_of_vecs被分配到栈上。 std::vector<T> 对象在 std::array 对象中分配,因此它们也在堆栈上(即,std::array 包含连续的 std::vector<T> 对象序列)。但是,这些std::vector<T>对象的内部缓冲区是分配在堆上的,而T对象是在该内存上构建的,即堆。

考虑以下代码:

struct S
{
    int _i;
    /* ... */
};

int main()
{
    S s1;
    S* s2 = new S{};
    return 0;
}

实例s1在栈上,它的所有成员也在栈上。 s2指向的内容分配在堆上,其所有成员也是如此。

现在,你的例子:

// all the instances of std::array<T, N> are on the heap,
// since std::vector allocates on the heap
std::vector<std::array<T, N>>

// the array itself is on the stack, and also the vector instances,
// but the content of the vectors is on the heap, as std::vector allocates on the heap
std::array<std::vector<T>,N>