开发者

STL containers on the stack and the heap

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&g开发者_Go百科t;();

Would resize using more heap?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜