When using push_back
of std::vector
, I can push an element of the vector itself without fear of invalidating the argument due to reallocation:
std::vector<std::string> v = { "a", "b" };
v.push_back(v[0]); // This is ok even if v.capacity() == 2 before this call.
However, when using emplace_back
, std::vector
forwards the argument to the constructor of std::string
so that copy construction happens in place in the vector. This makes me suspect that reallocation of the vector happens before the new string is copy constructed (otherwise it would not be allocated in place), thus invalidating the argument before use.
Does this mean that I cannot add an element of the vector itself with emplace_back
, or do we have some kind of guarantee in case of reallocation, similar to push_back
?
In code:
std::vector<std::string> v = { "a", "b" };
v.emplace_back(v[0]); // Is this valid, even if v.capacity() == 2 before this call?
You can just destroy it *after* emplaceing, oremplace the element first before copying/moving the old elements. – dyp Jul 23 '14 at 11:25