C++ journey: push_back vs. emplace_back


When working with containers like std::vector or std::deque, you’ll often need to add elements dynamically. C++ provides two commonly used methods for this operation: push_back and emplace_back. While they may appear similar, their internal workings and use cases differ significantly.


The Basics

  • push_back
    Adds a copy (or move) of the provided object to the container.
    Example:
  • emplace_back
    Constructs the object directly within the container, avoiding the need for a temporary object.
    Example:

Key Differences

  1. Construction vs. Insertion
    • push_back requires a fully constructed object as its argument, which is then copied or moved into the container.
    • emplace_back constructs the object directly within the container using the provided arguments.
  2. Performance
    • push_back involves at least one copy or move operation.
    • emplace_back avoids unnecessary construction and destruction of temporary objects, leading to better performance in scenarios involving complex objects.
  3. Ease of Use
    • push_back is straightforward when you already have a constructed object.
    • emplace_back can handle complex types more elegantly, as you only need to provide the arguments for construction.

Illustrative Example

Consider a std::vector of a custom class Item:
Using push_back:
Using emplace_back:
With push_back, the constructor of Item is invoked twice (once for the temporary object and once during insertion). With emplace_back, it is called only once.

When to Use?

  • Use push_back:
    • When you already have a constructed object to insert.
    • For simpler types where the performance difference is negligible.
  • Use emplace_back:
    • When constructing complex objects directly in the container.
    • To avoid unnecessary copies or moves, especially in performance-critical code.

Summary Table

Feature push_back emplace_back
Arguments Pre-constructed object Arguments for object construction
Performance May involve extra copies/moves Direct construction in place
Use Case Insert an existing object Construct object in container
While push_back is a classic and versatile method, emplace_back shines in scenarios involving complex types or performance-critical applications. Understanding their differences and applying them appropriately can lead to more efficient and readable code.