C++ Emplacing

Emplace operations are provided to make C++ code faster. They should be used when you want to add an object by constructing at the point of calling the emplace operation. For example, you may want to construct the object using its default constructor and then push it into the container. Or you may want to construct it using some parameters on the spot. Formerly, this involved the construction of a temporary object and then copying it into the container.

Many of the STL containers support emplacing. For example, vector now has emplace_back operation along with the old push_back operation, as well as emplace along with insert.

The good news is that the syntax of emplace and push/insert operations are the same, yet the efficiency of the former is much higher.

Emplace members forward the constructor's arguments in an automagical fashion. Here is an example:

#include <iostream>
#include <utility>
#include <string>
#include <unordered_map>

int main()
{
  std::unordered_map<unsigned int, std::string> m;
  m.emplace(std::make_pair(33, std::string("blood-curdling")));
  m.emplace(17, "built-in");

  for (const auto &p : m) {
    std::cout << p.first << " => " << p.second << '\n';
  }

  return 0;

Note: emplace operations seem to bypass ordinary constructors and use the copy constructor instead.

Emplacing in STL List and Deque Containers

You can emplace at the front or back with:

template <class... Args>  void emplace_front (Args&&... args);
template <class... Args>  void emplace_back (Args&&... args);

For emplacing with hint, the first argument is an iterator that the new item is to be constructed before:

template <class... Args>
iterator emplace (const_iterator position, Args&&... args);

[...]

Emplacing in STL Associtive Containers

std::set has an emplace(...) member function whose prototype is:

template <class... Args>  pair<iterator,bool> emplace (Args&&... args);

where args are the arguments to construct a new set element.

(If the function successfully inserts the element (because no equivalent element existed already in the set), the function returns a pair of an iterator to the newly inserted element and a value of true. Otherwise, it returns an iterator to the equivalent element within the container and a value of false.)

Analogously, ...


        

where args is the arguments forwarded to construct the new element (of type std::pair<const key_type, mapped_type>).

These can be one of: