Reputation: 443
In C++ there are two ways one can declare an object. For example:
// The first way
vector<int> *nums = new vector<int>;
// The second way
vector<int> nums;
People say that the first declaration allocates the object in the heap and the second on the stack. I can imagine how it works if the vector object is in the heap. The compiler would just find a free block in the heap to store the vector. But what would happen if the object is allocated on the stack as I keep pushing new elements to the vector? Will there be enough memory space? If not, how would the compiler find a sufficiently big memory block on the stack to store the vector when the size of the vector can change?
Upvotes: 8
Views: 262
Reputation: 11504
Putting vector
object on stack doesn't mean it will put its elements on stack. Check documentation:
Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it.
From: http://www.cplusplus.com/reference/vector/vector/
Upvotes: 10