When vectors are allocated, do they use memory on the heap or the stack?

Phelodas picture Phelodas · Nov 7, 2011 · Viewed 95.8k times · Source

Are all of the following statements true?

vector<Type> vect; //allocates vect on stack and each of the Type (using std::allocator) also will be on the stack

vector<Type> *vect = new vector<Type>; //allocates vect on heap and each of the Type will be allocated on stack

vector<Type*> vect; //vect will be on stack and Type* will be on heap. 

How is the memory allocated internally for Type in a vector or any other STL container?

Answer

Fred Foo picture Fred Foo · Nov 7, 2011
vector<Type> vect;

will allocate the vector, i.e. the header info, on the stack, but the elements on the free store ("heap").

vector<Type> *vect = new vector<Type>;

allocates everything on the free store.

vector<Type*> vect;

will allocate the vector on the stack and a bunch of pointers on the free store, but where these point is determined by how you use them (you could point element 0 to the free store and element 1 to the stack, say).