C++: Stack’s push() vs emplace() [duplicate]

To fully understand what emplace_back does, one must first understand variadic templates and rvalue references.

This is a fairly advanced, and deep concept in modern C++. On a map, it would be labeled “there be dragons”.

You say that you’re new to C++ and trying to learn this stuff. This may not be the answer you might be looking for, but you should skip this detail for now, and come back later after you’ve wrapped your brain around variadic templates and rvalue references. Then it should all make sense.

But if you insist: for a container containing simple, elementary types like integers, there’s little, if any difference. The difference comes when the container’s type is some large, sophisticated class, with a complicated constructor, and/or copy-constructor.

The end result of either push or emplace is exactly, 100%, the same. The container gets another element appended to it. The difference is where the element comes from:

1) push takes an existing element, and appends a copy of it to the container. Simple, straightforward. push always takes exactly one argument, the element to copy to the container.

2) emplace creates another instance of the class in the container, that’s already appended to the container. The arguments to emplace are forwarded as arguments to the container’s class’s constructor. Emplace can have either one argument, more than one argument, or no argument at all, if the class has a default constructor.

Note that when the class’s constructor takes one argument and it is not marked as explicit, it’s possible to abuse push and pass it a constructor argument, instead of an existing instance of the class. But let’s pretend that this option does not exist, it often leads to horrible code performance, especially with non-trivial classes.

So: if you want to add a copy of an existing instance of the class to the container, use push. If you want to create a new instance of the class, from scratch, use emplace.

Leave a Comment