8

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?

1
  • 3
    Great beginners question, and nicely stated. Commented Mar 18, 2015 at 21:59

1 Answer 1

10

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. Only the "wrapper" vector is in the stack. Internally it probably just contains a pointer. It would be different if it was an array, where the array size must remain fixed precisely because of the issues you ask.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.