Skip to content

std::initializer_list (C++11)

In a Nutshell

A lightweight, read-only proxy object that allows us to conveniently pass an arbitrary number of homogeneous initial values to containers or custom classes using braces {}.

#include <initializer_list>

Core API Quick Reference

OperationSignatureDescription
Constructorinitializer_list() noexceptCreates an empty list (usually implicitly constructed by the compiler)
Element Countstd::size_t size() const noexceptReturns the number of elements in the list
Begin Pointerconst T* begin() const noexceptPointer to the first element
End Pointerconst T* end() const noexceptPointer to one past the last element
Begin Iteratorconst T* begin(std::initializer_list<T> il) noexceptOverload of std::begin
End Iteratorconst T* end(std::initializer_list<T> il) noexceptOverload of std::end

Minimal Example

cpp
// Standard: C++11
#include <iostream>
#include <initializer_list>
#include <vector>

struct Container {
    std::vector<int> v;
    Container(std::initializer_list<int> l) : v(l) {}
    void append(std::initializer_list<int> l) {
        v.insert(v.end(), l.begin(), l.end());
    }
};

int main() {
    Container c = {1, 2, 3}; // 隐式构造 initializer_list
    c.append({4, 5});
    for (int x : c.v) std::cout << x << ' ';
}

Embedded Applicability: High

  • The underlying implementation typically contains only a pointer and a size (or two pointers), resulting in minimal memory overhead.
  • Copying a std::initializer_list does not copy the underlying array; it only copies the proxy object itself, incurring no additional allocation overhead.
  • The underlying array may reside in read-only memory, making it suitable for initializing static configuration tables stored in ROM.

Compiler Support

GCCClangMSVC
To be addedTo be addedTo be added

See Also


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05