Firstly, I'm aware of this question, but I don't believe I'm asking the same thing.
I know what std::vector<T>::emplace_back
does - and I understand why I would use it over push_back()
. It uses variadic templates allowing me to forward multiple arguments to the constructor of a new element.
But what I don't understand is why the C++ standard committee decided there was a need for a new member function. Why couldn't they simply extend the functionality of push_back()
. As far as I can see, push_back
could be overloaded in C++11 to be:
template <class... Args>
void push_back(Args&&... args);
This would not break backwards compatibility, while allowing you to pass N arguments, including arguments that would invoke a normal rvalue or copy constructor. In fact, the GCC C++11 implementation of push_back()
simply calls emplace_back anyway:
void push_back(value_type&& __x)
{
emplace_back(std::move(__x));
}
So, the way I see it, there is no need for emplace_back()
. All they needed to add was an overload for push_back()
which accepts variadic arguments, and forwards the arguments to the element constructor.
Am I wrong here? Is there some reason that an entirely new function was needed here?
v.emplace_back(123)
andv.push_back(123)
for example forvector<SomeType> v;
with implicit conversion fromint
. – Gene Bushuyev