Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::initializer_list — access to list elements

std::initializer_list<T> accepts brace-enclosed elements as a read-only sequence. Copying the list object neither copies its elements nor extends their lifetime.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <initializer_list>
std::initializer_list<T> values = {value1, value2};

std::initializer_list<T>, declared in <initializer_list>, provides access to an array of const T elements. A parameter of this type lets callers write sum({2, 4, 6}). However, not every brace initialization creates a std::initializer_list.

In the C++23 interface, size() reports the element count, while begin() and end() enable iteration, including a range-based loop. A default-constructed list is empty. Elements cannot be modified through this interface; copying the list does not copy the array.

The compiler creates a backing array and copy-initializes its elements. Narrowing conversions are forbidden: std::initializer_list<int> x{1.5}; is ill-formed. Brace notation is language syntax, whereas std::initializer_list is a library type.

Initializing a list object can extend the backing array's lifetime, similarly to binding a reference to a temporary. For a function argument, the array survives until the end of the full-expression containing the call. Do not retain the list or its iterators for later use: copying the parameter does not extend that lifetime. Do not return a list backed by a local backing array.

Examples

#include <initializer_list>
#include <iostream>

int sum(std::initializer_list<int> values) {
    int total = 0;
    for (int value : values) {
        total += value;
    }
    return total;
}

int main() {
    std::cout << sum({2, 4, 6}) << '\n';
    std::cout << sum({}) << '\n';
}

Result

12
0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources