Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to use emplace operations of C++11

📅 2014-Oct-09 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp11, emplace, emplace_back, vector ⬩ 📚 Archive

C++11 introduced emplace operations on many of the STL containers. For example, vector now has emplace_back operation along with the old push_back operation.

Emplace operation is provided for convenience, to make writing code in C++ a bit more easier. It 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. The older alternative for this involved the construction of a temporary object and then copying it into the container.

The code below shows a simple example of these scenarios:

// Sample code to demonstrate emplace_back operation of vector

#include <iostream>
#include <vector>

struct Creature
    Creature() : is_mammal_(false), age_(0), population_(0)
        std::cout << "Default constructor called\n";

    Creature(bool is_mammal, int age, int population)
        : is_mammal_(is_mammal), age_(age), population_(population)
        std::cout << "3-arg constructor called\n";

    bool is_mammal_;
    int age_;
    int population_;

typedef std::vector<Creature> CreatureVec;

int main()
    CreatureVec cv;
    cv.emplace_back(true, 10, 9999);

    return 0;