Double-Ended Queues using std::deque

Benefits of using emplace over insert

What are the advantages of using emplace_front() or emplace_back() instead of push_front() or push_back()?

Vector art representing computer hardware

The emplace_front() and emplace_back() methods of std::deque construct elements in-place at the front or back of the deque, while push_front() and push_back() copy or move an existing object into the deque.

Using emplace_front() or emplace_back() can be more efficient because:

  1. It avoids creating a temporary object. With push_front() or push_back(), you often need to create an object before adding it to the deque. emplace_front() and emplace_back() construct the object directly in the deque's memory.
  2. It avoids the copy or move operation. After creating the temporary object, push_front() or push_back() need to copy or move it into the deque. emplace_front() and emplace_back() avoid this step.

Here's an example:

#include <deque>
#include <string>
#include <iostream>

struct User {
  std::string name;
  int id;
  User(std::string name, int id)
    : name(name), id(id) {
    std::cout << "Constructing User "
      << name << "\n";
  }
  User(const User& other)
    : name(other.name), id(other.id) {
    std::cout << "Copying User "
      << name << "\n";
  }
};

int main() {
  std::deque<User> users;

  users.emplace_back("Alice", 1);

  User bob("Bob", 2);
  users.push_back(bob);
}
Constructing User Alice
Constructing User Bob
Copying User Bob

When using emplace_back(), the User object is constructed directly in the deque. When using push_back(), the User object is first constructed, then copied into the deque.

However, the performance difference is only significant for types that are expensive to copy or move. For simple types like int or double, there's likely no noticeable difference.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved