Consider this code:
std::string &s = v;
std::cout << s << std::endl;
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4
The act of modifying the container is not prohibited just because you acquired an iterator, reference, or pointer by some means. It is the iterator, reference, or pointer itself that is potentially invalidated.
§184.108.40.206 [vector.modifiers] (includes the
push_back member family)
- Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid. If an exception is thrown other than by the copy constructor, move constructor, assignment operator, or move assignment operator of
Tor by any InputIterator operation there are no effects. If an exception is thrown while inserting a single element at the end and
Tis CopyInsertable or
is_nothrow_move_constructible<T>::valueis true, there are no effects. Otherwise, if an exception is thrown by the move constructor of a non-CopyInsertable
T, the effects are unspecified.
If no resize happens only references, pointers, and iterators (including the end-iterator) past the insertion point are invalid. Great, but what happens if a reallocation happens? Interestingly, we find that in:
- Remarks: Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. No reallocation shall take place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().
I'm not entirely convinced this completely answers your question, however. If your wondering what happened to the prior memory that occupied the vector, that's up to the standard library, but it no longer contains viable content. The container no longer owns the memory (as far as you know), and neither do you.