C++ std::list::emplace

The std::list::emplace function constructs and inserts a new element into the std::list at the specified position. Unlike insert, which requires an already constructed object, emplace directly constructs the object in-place using the provided arguments, avoiding unnecessary copies or moves.


Syntax of std::list::emplace

</>
Copy
template <class... Args>
iterator emplace(const_iterator position, Args&&... args);

Parameters

ParameterDescription
positionA constant iterator specifying the position in the list where the new element will be constructed and inserted.
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

The function returns an iterator pointing to the newly constructed element in the list.

Exceptions

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

  • If memory allocation fails.
  • If the constructor of the element 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

Example 1: Inserting a Simple Element

This example demonstrates how to use emplace to insert a simple element into a list:

Program

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

int main() {
    std::list<int> myList = {10, 20, 30};

    // Insert 15 at the second position
    auto it = myList.emplace(++myList.begin(), 15);

    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 initialized with the elements {10, 20, 30}.
  2. The emplace function is called with ++myList.begin(), which points to the second position in the list.
  3. A new element, 15, is constructed and inserted at this position.
  4. A range-based for loop iterates through the list and prints its contents.

Output:

List contents: 10 15 20 30

Example 2: Inserting a Complex Object

This example demonstrates how to use emplace to insert a complex object into a 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;

    // Insert Person objects into the list
    people.emplace(people.end(), "Arjun", 30);
    people.emplace(people.end(), "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. The emplace function is used to construct and insert two Person objects (“Arjun” and “Ram”) at the end of the list.
  3. 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 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(myList.end(), 10); // Success
        myList.emplace(myList.end(), -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 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.

Output:

Exception: Negative value not allowed
List contents: 10