Search code examples
c++vectorstlheap-memorystack-memory

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


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?


Solution

  • 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 (except vect pointer, which is on the stack).

    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).