C++ std::list::emplace_back

The std::list::emplace_back function constructs and inserts a new element at the end of a std::list. Unlike push_back, which requires an already constructed object, emplace_back constructs the object in-place using the provided arguments, avoiding unnecessary copies or moves. This makes it especially useful for adding complex objects to the list.


Syntax of std::list::emplace_back

</>
Copy
template <class... Args>
void emplace_back(Args&&... args);

Parameters

ParameterDescription
args...Arguments to forward to the constructor of the element being added. These arguments are used to construct the element directly in the list.

Return Value

This function does not return a value. It modifies the list by adding a new element at the end.

Exceptions

The std::list::emplace_back function may throw exceptions in the following cases:

  • If memory allocation fails.
  • If the constructor of the object being added throws an exception.

The function provides strong exception safety. If an exception occurs, the state of the list remains unchanged.


Examples for std::list::emplace_back

Example 1: Adding an Element Using emplace_back

This example demonstrates how to use emplace_back to add a simple element to the end of a list:

Program

</>
Copy
#include <iostream>
#include <list>

int main() {
    std::list<int> myList;

    myList.emplace_back(10); // Add 10 to the end of the list
    myList.emplace_back(20); // Add 20 to the end of the list

    std::cout << "List contents: ";
    for (const auto& elem : myList) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. A std::list named myList is created and is initially empty.
  2. The emplace_back function is used to add two elements (10 and 20) to the end of the list. Each element is constructed directly in the list.
  3. A range-based for loop is used to iterate through the list and print its contents.

Output:

List contents: 10 20

Example 2: Adding Complex Objects Using emplace_back

This example demonstrates how to use emplace_back to construct and add complex objects directly to the list:

Program

</>
Copy
#include <iostream>
#include <list>
#include <string>

struct Person {
    std::string name;
    int age;

    Person(const std::string& name, int age) : name(name), age(age) {}
};

int main() {
    std::list<Person> people;

    // Construct and add Person objects in-place
    people.emplace_back("Arjun", 30);
    people.emplace_back("Ram", 25);

    for (const auto& person : people) {
        std::cout << person.name << " (" << person.age << " years old)" << std::endl;
    }

    return 0;
}

Explanation:

  1. The Person struct is defined with two members: name (a string) and age (an integer).
  2. A std::list of Person objects named people is created.
  3. The emplace_back function is used to construct and add two Person objects (“Arjun” and “Ram”) directly in the list.
  4. A range-based for loop iterates through the list and prints the details of each Person.

Output:

Arjun (30 years old)
Ram (25 years old)

Example 3: Exception Safety

This example demonstrates how emplace_back handles exceptions during object construction:

Program

</>
Copy
#include <iostream>
#include <list>
#include <stdexcept>

struct Faulty {
    int value;

    Faulty(int v) {
        if (v < 0) {
            throw std::invalid_argument("Negative value not allowed");
        }
        value = v;
    }
};

int main() {
    std::list<Faulty> myList;

    try {
        myList.emplace_back(10); // Success
        myList.emplace_back(-1); // Throws an exception
    } catch (const std::exception& e) {
        std::cout << "Exception: " << e.what() << std::endl;
    }

    std::cout << "List contents: ";
    for (const auto& elem : myList) {
        std::cout << elem.value << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation:

  1. The Faulty struct has a constructor that throws an exception if a negative value is passed.
  2. The emplace_back function is used to add a valid object (10), which succeeds.
  3. An attempt to add an invalid object (-1) throws an exception. The exception is caught and handled gracefully.
  4. After the exception, the state of the list remains unchanged, demonstrating the strong exception safety of emplace_back.

Output:

Exception: Negative value not allowed
List contents: 10