As per: https://en.cppreference.com/w/cpp/container/vector/push_back and I quote:
If the new size() is greater than capacity() then all iterators and
references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.
So basically when doing the push_back
the vector creates, if needed, a new buffer of bigger capacity, moves all the std::unique_ptr
from the old buffer to the new, add the new unique_ptr
and deletes the old buffer.
You have a reference to an element in the old buffer, which dangles. A dangling reference is undefined behavior and everything can happen, for example you can have garbage data being printed or a crash.
Edit: I explain the issue, Oblivion, in their answer, explains a possible remediation using shared_ptr
which might be appropriate or not given the use case which is unknown.