堆栈和堆上的 STL 容器

发布于 2024-08-09 11:33:29 字数 253 浏览 1 评论 0原文

如果 std::vector 和朋友正在自行调整大小,这是否意味着如果我像这样声明一个向量:

std::vector<string> myvec;

那么它将使用更多堆栈调整大小,而:

std::vector<string> *myvec = new std::vector<string>();

会使用更多堆调整大小吗?

If std::vector and friends are self resizing, does that mean if I declare a vector like so:

std::vector<string> myvec;

Then it'll resize using more stack, whereas:

std::vector<string> *myvec = new std::vector<string>();

Would resize using more heap?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

樱花细雨 2024-08-16 11:33:30

在第一种情况下,您在堆栈上创建向量。这并不意味着所有向量内部对象也都在堆栈上。事实上,向量仍然会分配仅在堆上保存对象所需的内存。这是因为,要在堆栈上分配,您应该知道要创建多少个对象。但此信息不可用,因此唯一剩下的选项是从堆中为所包含的对象分配内存。

In the first case, you are creating the vector on stack. That doesn't mean that all the vectors internal objects are on stack as well. In fact, vector will still allocate the memory required to hold the objects on heap only. This is because, to allocate on stack you should know how many objects to create. But this information is not available, so the only remaining option is to allocate the memory for the contained object from heap.

∞觅青森が 2024-08-16 11:33:30

std::vector 始终在堆上分配其缓冲区。因此,无论向量本身分配在哪里,调整大小都只会影响堆。

std::vector always has its buffer allocated on heap. So regardless of where the vector itself is allocated resizing it will only affect the heap.

迟月 2024-08-16 11:33:29

向量在其内部的堆上分配。

对于基于堆栈的 bector,您在堆栈中唯一需要支付的费用是几个字节,内部缓冲区将始终从堆中分配。

因此,当您执行 vec = new vector() 时,您会有效地分配少量数量,这可能不是很好。

Vectors allocate on the heap in their internals.

The only thing you pay for in the stack for a stack based bector is a couple of bytes, the inner buffer will always be allocated from the heap.

So effectively when you do a vec = new vector() you are allocating a small quantity, which may not be really good.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文