简体   繁体   English

C++ 向量 memory 分配

[英]C++ vector memory allocation

You can't have:你不能有:

int array[1000000];

but you can make a vector and store those 1000000 elements.但是您可以制作一个vector并存储这 1000000 个元素。

Is this because the array is stored on the stack and it will not have enough space to grow?这是因为数组存储在堆栈上并且没有足够的空间来增长吗?

What happens when you use the vector instead?当您改用向量时会发生什么?

How does it prevent the issue of storing too many elements?它如何防止存储过多元素的问题?

As defining those as global or in other places might not go in the stack, I assume we are defining int array[1000000] or std::vector<int> array(1000000) in a function definition, ie local variables.由于将它们定义为全局或其他地方可能不在堆栈中的 go ,我假设我们在 function 定义中定义int array[1000000]std::vector<int> array(1000000) ,即局部变量。

For the former, yes you're right.对于前者,是的,你是对的。 It is stored in the stack and due to stack space limitation, in most environment it is dangerous.它存储在堆栈中,由于堆栈空间的限制,在大多数环境中它是危险的。

On the other hand, in most of standard library implementations, the latter only contains a size, capacity and pointer where the data is actually stored.另一方面,在大多数标准库实现中,后者仅包含实际存储数据的大小、容量和指针。 So it would take up just a couple dozen bytes in the stack, no matter how many elements are in the vector.因此,无论向量中有多少元素,它都只会占用堆栈中的几十个字节。 And the pointer is generated from heap memory allocation( new or malloc ), not the stack.并且指针是从堆 memory 分配( newmalloc )而不是堆栈生成的。

Here is an example of how many bytes it takes up in the stack for each.是每个在堆栈中占用多少字节的示例。

And here is a rough visualization.这是一个粗略的可视化。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM