How to use emplace operations of C++11

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);
cv.emplace_back();
return 0;
}

view raw
emplace_back.cpp
hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.