I noticed that emplace_back
in an std::vector
changes the address of previous vector elements. Why?
3 Answers
From the backing storage perspective whether you push
or emplace
doesn't matter. The difference there is for the argument.
Therefore the usual relocation mechanism are in place. They will move the elements when currently allocated contiguous storage is exhausted.
The rules for iterator invalidation stay the same. Checkout "Iterator invalidation" on http://en.cppreference.com/w/cpp/container/vector.
Unfortunately that’s standard: If the new size() is greater than capacity() then all iterators and references are invalidated.

- 1,781
- 17
- 20
If the current capacity of the backing store for the vector cannot accommodate a new element then a new, larger backing store must be allocated, all the existing elements moved to it, then the new element can be constructed in place.
Using emplace_back()
doesn't change the fact that the backing store has to be large enough to fit the new element.

- 333,147
- 50
- 533
- 760