How do I use emplace vs push with std::deque?

In C++, both emplace and push are methods provided to insert elements into a std::deque. However, they work differently in terms of how they handle object construction and how efficiently they manage memory.

Using push vs emplace

The push_back and push_front methods of std::deque are used to insert elements at the end and at the beginning of the deque, respectively. They take an object as a parameter, which means that the object will be copied or moved into the deque.

On the other hand, emplace_back and emplace_front directly construct the object in-place. This means that instead of copying or moving an existing object, emplace takes the constructor arguments for the object and creates it directly in the deque, which can lead to better performance, especially for complex objects.

Example of using emplace vs push

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

int main() {
    std::deque<:string> myDeque;

    // Using push_back
    myDeque.push_back("Hello");
    myDeque.push_back("World");

    // Using emplace_back
    myDeque.emplace_back("Welcome");
    myDeque.emplace_back("to C++");

    // Display the contents of the deque
    for (const auto &word : myDeque) {
        std::cout << word << " ";
    }

    return 0;
}
    

C++ std::deque emplace push performance object construction