3 ms·
I would summarize it as: use `push_back` when you're pushing something, use `emplace_back` when you want to construct something in the space at the end of the c
by sfink 2y ago
I would summarize it as: use `push_back` when you're pushing something, use `emplace_back` when you want to construct something in the space at the end of the collection. It just so happens that their functionality overlaps, and there really isn't a strong reason to use `push_back(Widget(ctor_arg1, ctor_arg2))` vs `emplace_back(ctor_arg1, ctor_arg2)` with a movable `Widget`, so it comes down to readability and communicating intention. And those will depend on the situation.
Mentioning `Widget` is definitely more explicit, so I agree with the author that `push_back(Constructor(...))` is usually better. Semantically, it's also usually simpler to think of "push a newly-constructed Widget" vs "construct a Widget in the next element of the vector and lengthen the vector to include it".
- layer8 2y agoMaybe construct_back would have been a better name.
- jeffreygoesto 2y agoIn our pre-C++11 library we had containers with a append_uninitialized_element() and called placement new on that with an explicit ctor. While syntactically phony it had an unambigous semantic. Code review had to check (remember, pre clang-tidy times) that the method way never used alone.
- tmyklebu 2y agoCompile time is another reason to prefer push_back, which is a function, to emplace_back, which is a function template.