Skip to content

std::initializer_list (C++11)

In a Nutshell

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

#include <initializer_list>

Core API Quick Reference

OperationSignatureDescription
Constructioninitializer_list() noexceptCreates an empty list (typically 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) noexceptOverloaded std::begin
End iteratorconst T* end(std::initializer_list<T> il) noexceptOverloaded 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 length (or two pointers), resulting in minimal memory overhead
  • Copying std::initializer_list does not copy the underlying array; it only copies the proxy object itself, with no additional allocation overhead
  • The underlying array may reside in read-only memory, making it suitable for initializing ROM-able static configuration tables

Compiler Support

GCCClangMSVC
TBATBATBA

See Also


Some content referenced from cppreference.com, licensed under CC-BY-SA 4.0

Built with VitePress