STL containers on the stack and the heap

10,513

Solution 1

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.

Solution 2

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.

Solution 3

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.

Share:
10,513
Benj
Author by

Benj

I'm a C++ programmer (these days) doing mainly win32 stuff. Although there'll always be a secret place in my heart for a bit of down and dirty perl programming :-)

Updated on July 09, 2022

Comments

  • Benj
    Benj almost 2 years

    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?