这个嵌套数组是使用堆栈还是堆内存? [英] Is this nested array using stack or heap memory?

查看:186
本文介绍了这个嵌套数组是使用堆栈还是堆内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个声明并使用嵌套在向量中的数组

Say I have this declaration and use of array nested in a vector

const int MAX_LEN = 1024;
typedef std::tr1::array<char, MAX_LEN> Sentence;
typedef std::vector<Sentence> Paragraph;

Paragraph para(256);
std::vector<Paragraph> book(2000);

我假设 Sentence 的内存为在堆栈上。
是吗?
向量 para 的内存是什么?是在堆栈,即我应该担心,如果我的para太大了?

最后一本书的记忆是什么?这必须在堆上我猜,但嵌套数组在堆栈上,不是吗?

其他问题

的段落连续?

book 的内存是否连续?

I assume that the memory for Sentence is on the stack.
Is that right? What about the memory for vector para? Is that on the stack i.e. should I worry if my para gets too large?
And finaly what about the memory for book? That has to be on the heap I guess but the nested arrays are on the stack, aren't they?
Additional questions
Is the memory for Paragraph contiguous?
Is the memory for book contiguous?

推荐答案

没有堆栈。不要考虑堆栈。重要的是一个给定的容器类是否执行任何动态分配。

There is no stack. Don't think about a stack. What matters is whether a given container class performs any dynamic allocation or not.

std :: array< T,N& c>不使用任何动态分配,它是围绕自动分配的 T [N] 的一个很好的东西。

然而,任何你放在向量 将由向量自己的分配器,在默认情况下(通常)执行动态分配 :: operator new

Anything you put in a vector will however be allocated by the vector's own allocator, which in the default case (usually) performs dynamic allocation with ::operator new().

简而言之,向量< array< char,N>> 非常类似于向量< int> :分配器简单地为数组 (或 int ),因为它需要保存并构造该内存中的元素。冲洗并重复嵌套向量。

So in short, vector<array<char,N>> is very simiar to vector<int>: The allocator simply allocates memory for as many units of array<char,N> (or int) as it needs to hold and constructs the elements in that memory. Rinse and repeat for nested vectors.

对于您的其他问题: vector<对于 T 来说,T>< / code>绝对不连续。它仅仅对于向量 是连续的,但是仅包含内向量的小的记账部分。内向量的实际内容由内向量的分配器分配,并且对于每个内向量分开。一般来说,向量< S> 对于类型 S 是连续的,没有其他。

For your "additional questions": vector<vector<T>> is definitely not contiguous for T at all. It is merely contiguous for vector<T>, but that only contains the small book-keeping part of the inner vector. The actual content of the inner vector is allocated by the inner vector's allocator, and separately for each inner vector. In general, vector<S> is contiguous for the type S, and nothing else.

我实际上不确定向量< array< U,N>> - 它可能对于 U ,因为数组除了包含 U [N] 之外没有理由包含任何数据,我不知道这是否是必须的。

I'm not actually sure about vector<array<U,N>> -- it might be contiguous for U, because the array has no reason to contain any data besides the contained U[N], but I'm not sure if that's mandatory.

你可能想问一个单独的问题,这是一个很好的问题!

You might want to ask that as a separate question, it's a good question!

这篇关于这个嵌套数组是使用堆栈还是堆内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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