Search code examples
c++c++11stdvectoremplace

How does `emplace_back` in an `std::vector` work?


I noticed that emplace_back in an std::vector changes the address of previous vector elements. Why?


Solution

  • 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.