C ++ std :: vector内存/分配 [英] C++ std::vector memory/allocation

查看:188
本文介绍了C ++ std :: vector内存/分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

贝利先生在先前关于向量容量的问题中说:

在当前的C ++中,可以保证在调用保留后不会发生任何重新分配,直到插入的大小超过了先前调用保留的值为止.在保留调用之前或之后,当大小在上一个保留调用的值和容量之间时,如果允许的话,允许实现者尽早重新分配.

In current C++ you are guaranteed that no reallocation occurs after a call to reserve until an insertion would take the size beyond the value of the previous call to reserve. Before a call to reserve, or after a call to reserve when the size is between the value of the previous call to reserve and the capacity the implementation is allowed to reallocate early if it so chooses.

因此,如果我理解正确,为了确保在超出容量之前不会发生任何重新分配,我是否必须预留两次?你能澄清一下吗?

So, if I understand correctly, in order to assure that no reallocation happens until capacity is exceeded, I must do reserve twice? Can you please clarify it?

我将向量用作这样的内存堆栈:

I am using vector as a memory stack like this:

std::vector<double> memory;
memory.reserve(size);
memory.insert(memory.end(), matrix.data().begin(), matrix.data().end()); // smaller than size
memory.resize(memory.capacity(), 0);

我需要保证上面没有发生重新分配.

I need to guarantee that reallocation does not happen in the above.

谢谢.

ps:我也想知道,除了向量以外,是否还有更好的方法来以类似方式管理内存堆栈

ps: I would also like to know if there is a better way to manage memory stack in similar manner other than vector

推荐答案

我认为您读错了该声明.储备金允许将capacity设置为比所保留的金额更大的金额.特殊的语言是,如果您保留的存储量比上次(但在达到当前容量之前)要多,则允许重新分配实现.

I think you're reading the statement wrong. Reserve is allowed to set capacity to a larger amount than what you reserved. The special language is to allow an implementation to reallocate if you're reserving more than you did the last time, but before you've reached the current capacity.

这篇关于C ++ std :: vector内存/分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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