For std::vector<std::string> v, how do v.push_back("abc") and v.emplace_back("abc") differ?
Correct answer
C. emplace_back builds the string in place from the literal, push_back moves a temporary in
15 views
C. emplace_back builds the string in place from the literal, push_back moves a temporary in
15 views
emplace_back forwards its arguments to the element's constructor and builds the object directly in the vector's storage, avoiding the temporary that push_back creates. For a std::string initialised from a literal this usually saves one move or copy. Neither call stops iterators from being invalidated on reallocation, and emplace_back is not always a drop-in replacement when an initializer_list overload exists.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is C? Ask here and get an explanation.