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

3
我知道`std::vector`在堆上分配动态内存,而`std::array`则在栈上分配内存。
但是当我将这两个容器合并时,内存是如何分配的呢?
例如:
std::vector<std::array<T, N>> a;

或者

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

作者:

std::vector<std::array<T, N>> a;
  • a的恢复对象序列/数组是否完全存储在堆上,还是部分共享于堆和栈之间?

作者:

std::array<std::vector<T>,N> a;
  • a的恢复对象序列/数组完全存储在堆栈上,还是其中有一部分共享于堆和栈之间?

非常感谢您的参与。

2个回答

3

简单来说,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::arrayNstd::vector<T>对象直接作为数据成员存储在自己内部。因此,如果包含它们的std::array分配在栈上,则std::vector<T>对象也将在栈上。但每个向量的内部缓冲区都是在堆上分配的,因此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对象是在该内存上构建的,即在堆上。


2
考虑下面的代码:

以下是代码:

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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接