Compare them, using the reference:
https://en.cppreference.com/w/cpp/container/vector/emplace_back
https://en.cppreference.com/w/cpp/container/vector/push_back
push_back
takes a reference or rvalue reference.
emplace_back
takes a parameter pack. emplace_back
is used to construct a type "in place", whereas push_back
can only move or copy an object, not construct it in place.
(Note that push_back
can implicitly call a constructor function, but this causes two function calls. A constructor function call followed by a move or copy. That is not the same for emplace_back
which calls a constructor only.)
For example, consider a non-trivial type:
struct ContainsAFewThings
{
ContainsAFewThings(a, b)
: a(a)
, b(b)
{
}
int a;
int b;
}
We can construct it directly using emplace_back
.
std::vector<ContainsAFewThings> vect;
vect.emplace_back(1, 2);
This performs one call to the constructor function, and no calls to a move or copy constructor. The alternative with push_back
calls the constructor function, then copy or move:
std::vector<ContainsAFewThings> vect;
vect.push_back(ContainsAFewThings(1, 2)); // push_back with explicit constructor
// does the same thing as this:
vect.push_back(1, 2); // hidden impicit constructor call here!
To understand more, learn about perfect forwarding and "The Forwarding Problem" in C++. There is a discussion about it here.