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:

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s