C++ std::vector<;类型的数组是如何工作的;std::数组<;T、 N>&燃气轮机;或std::数组<;标准::向量<;T>;,N>;存储在内存中?

C++ std::vector<;类型的数组是如何工作的;std::数组<;T、 N>&燃气轮机;或std::数组<;标准::向量<;T>;,N>;存储在内存中?,c++,arrays,memory,stack,heap-memory,C++,Arrays,Memory,Stack,Heap Memory,我知道std::vector在堆上分配动态内存。我还知道std::array在堆栈上分配内存 但是当我将两个容器合并在一起时,内存是如何分配的呢 比如f.e.: std::vector<std::array<T, N>> a; a的恢复对象序列/数组是否完全存储在堆栈上,还是在堆栈和堆之间共享部分 非常感谢您的参与。基本上,std::array将T对象存储在对象本身中,就像它们是普通数据成员一样,而std::vector在堆上分配缓冲区,并在该内存上构造T对象 当谈

我知道
std::vector
在堆上分配动态内存。我还知道
std::array
在堆栈上分配内存

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

比如f.e.:

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

非常感谢您的参与。

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

当谈到
std::array
时,由于
T
对象位于
std::array
本身内部,因此这些
T
对象是在堆上还是堆栈上分配取决于
std::array
的分配位置:

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

  • 如果
    std::array
    是在堆上分配的(例如,
    newstd::array
    ),那么
    T
    对象也是如此


std::vector
向量将所有
std::array
对象存储在其内部缓冲区中,该缓冲区在堆上分配。也就是说,假设arrs的vec具有自动存储持续时间:


对象
arr\u of_vecs
在堆栈上分配。
std::vector
对象在
std::array
对象中分配,因此它们也在堆栈上(即
std::array
包含一个连续的
std::vector
对象序列)。但是,这些
std::vector
对象的内部缓冲区分配在堆上,而
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>
//std::array的所有实例都在堆上,
//因为std::vector在堆上分配
向量
//数组本身在堆栈上,还有向量实例,
//但是向量的内容在堆上,就像std::vector在堆上分配一样
std::数组
std::array<std::vector<T>,N> a;
std::vector<std::array<T, N>> vec_of_arrs;
std::array<std::vector<T>,N> arr_of_vecs;
struct S
{
    int _i;
    /* ... */
};

int main()
{
    S s1;
    S* s2 = new S{};
    return 0;
}
// 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>