Containers on Stack or Heap?

std::vector 

std::vector<string> myvec;

In this vector declaration is inside a function, it means the vector is created on the 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.

Vector (probably) contains a pointer to a heap allocated chunk of storage where it keeps all the objects placed inside the vector. 

This is the same case for all other containers too except std::array where the fixed size is known. 


unordered_set 
set 
unordered_map
map
list

Reference

STL containers on stack or heap






Comments