allocating a vector on the heap question

If I allocate an empty std::vector on the heap, that allocates memory for a vector object with no elements. When I add elements to the vector, it may have to re-allocate itself to get more memory. But the original pointer I have to it should always be valid until I delete it.
[ Question1 ] How is it that the vector can re-allocate memory for itself, but ensure its original address in memory stays constant?

More details:

1
2
3
4
5
6
7
8
9
10
11
12
13
vector<int>* ptrVec = new vector<int>();  

// ptrVec should be valid until it is deleted

// let's say some more heap memory allocations occur that mean the heap memory that the vector could expand into is used up, eg.

   SomeObject* p = new SomeObject();  // etc.

// force expansion of vector
for ( int i = 0; i < 10000; ++i )
    ptrVec->push_back( 4 );

// at this point, will I get an out-of-memory exception? 


[Question2] Is it better to avoid allocating vectors on the heap because of this possibility?
The vector manages its own storage space internally, abstracted away from the user. Your pointer will always be valid because it is external to the vector implementation. Vectors were designed so that users can just use them without such worries.
In reference to your question posed as a comment in your source code:

According to

http://www.cplusplus.com/reference/stl/vector/push_back/

the re-allocation can cause the bad_alloc exception. The vector will still be valid, it just will not include the element you attempted to add.

So the answer to question 2 (IMHO) would be to use the heap if it makes sense, just don't assume space was allocated when you add new elements to the container.
The pointer to the vector remains valid, but pointers to separate elements might not (thus why an iterator is generally useless after elements are added or removed).

It's always possible to use the reserve(int) function though. If you have a (somewhat-tight) upperbound on the amount of elements for the vector, you can reserve that amount. It will prevent any nasty side-effects caused by "moving to fit".
Thanks for all replies, that's cleared things up.
Topic archived. No new replies allowed.