views:

388

answers:

3

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?

A: 

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.

sharptooth
+8  A: 

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.

Arkaitz Jimenez
Ah ok, so do vectors declared on the stack delete the memory they've used once they go out of scope then?
Benj
@Benj: Yes, they will cleanup the memory when they go out of scope.
Naveen
@Benj: do note that vectors only clean up the memory they allocated themselves. If you add heap allocated objects (with 'new') to a vector, then you are responsible for calling 'delete' on them. Maybe you already knew this, but I wanted to mention it just in case...
StackedCrooked
@StackedCrooked: Thanks for that, good to know.
Benj
+2  A: 

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.

Naveen