utility_initializer_list
utility_initializer_list (std::initializer_list 유틸리티)
이 페이지는 C++ 표준 라이브러리의 std::initializer_list 템플릿 클래스에 대해 다루고 있어요. std::initializer_list는 중괄호로 묶인 초기화 목록을 나타내는 가벼운 프록시 객체로, 생성자나 함수 인자 등에서 목록 초기화를 가능하게 해 주는 핵심 도구예요. 여기서는 그 정의, 멤버 타입, 멤버 함수, 비멤버 함수, 예제, 그리고 결함 보고까지 자세히 살펴볼게요.
출처: cppreference
본문
(멤버 초기화 목록(member initializer list)과 혼동하지 마세요.)
<initializer_list> 헤더에 정의됨 |
||
|---|---|---|
template < class T > class initializer_list; |
(C++11부터) |
std::initializer_list<T> 타입의 객체는 const T 타입 객체들의 배열(읽기 전용 메모리에 할당될 수 있음)에 접근을 제공하는 가벼운 프록시 객체예요.
std::initializer_list 객체는 다음과 같은 상황에서 자동으로 생성돼요:
- 중괄호로 묶인 초기화 목록이 객체를 목록 초기화(list-initialize)하는 데 사용되고, 해당 생성자가
std::initializer_list매개변수를 받을 때 - 중괄호로 묶인 초기화 목록이 대입 연산의 오른쪽 피연산자나 함수 호출 인자로 사용되고, 해당 대입 연산자/함수가
std::initializer_list매개변수를 받을 때 - 중괄호로 묶인 초기화 목록이
auto에 바인딩될 때 (범위 기반 for 루프에서도 포함)
std::initializer_list는 포인터 쌍 또는 포인터와 길이로 구현될 수 있어요. std::initializer_list를 복사해도 해당 초기화 목록의 뒷받침 배열(backing array)은 복사되지 않아요.
std::initializer_list의 명시적 특수화 또는 부분 특수화를 선언하면 프로그램의 형식이 잘못된(ill-formed) 것으로 간주돼요.
멤버 타입 (Member types)
| 이름 | 정의 |
|---|---|
value_type |
T |
reference |
const T & |
const_reference |
const T & |
size_type |
std::size_t |
iterator |
const T * |
const_iterator |
const T * |
멤버 함수 (Member functions)
| (생성자) | 빈 초기화 목록을 생성해요 (공개 멤버 함수) [편집] |
|---|---|
| 용량 (Capacity) | |
size |
초기화 목록의 요소 수를 반환해요 (공개 멤버 함수) [편집] |
empty |
std::initializer_list가 비어 있는지 확인해요 (공개 멤버 함수) [편집] |
| 반복자 (Iterators) | |
begin |
첫 번째 요소를 가리키는 포인터를 반환해요 (공개 멤버 함수) [편집] |
end |
마지막 요소 바로 다음을 가리키는 포인터를 반환해요 (공개 멤버 함수) [편집] |
data |
첫 번째 요소를 가리키는 포인터를 반환해요 (공개 멤버 함수) [편집] |
비멤버 함수 (Non-member functions)
std::initializer_list를 위해 오버로드된 자유 함수 템플릿 |
|---|
rbegin crbegin (C++14) |
rend crend (C++14) |
참고 사항 (Notes)
| 기능 테스트 매크로 | 값 | 표준 | 기능 |
|---|---|---|---|
__cpp_initializer_lists |
200806L | (C++11) | 목록 초기화 및 std::initializer_list |
__cpp_lib_initializer_list |
202511L | (C++26) (DR11) | std::initializer_list의 data 및 empty 멤버 함수; 불필요한 std::initializer_list 자유 함수 제거 [1] |
- [1] 2026-05-27 기준으로 libstdc++는 P3016R6의 함수 추가 및 제거를 C++11에 대한 결함 보고로 처리하지 않았으며, 해당 변경 사항을 C++26부터만 적용해요.
예제 (Example)
#include <cassert>
#include <initializer_list>
#include <iostream>
#include <vector>
template<class T>
struct S
{
std::vector<T> v;
S(std::initializer_list<T> l) : v(l)
{
std::cout << "constructed with a " << l.size() << "-element list\n";
}
void append(std::initializer_list<T> l)
{
v.insert(v.end(), l.begin(), l.end());
}
std::pair<const T*, std::size_t> c_arr() const
{
return {&v[0], v.size()}; // copy list-initialization in return statement
// this is NOT a use of std::initializer_list
}
};
template<typename T>
void templated_fn(T) {}
int main()
{
S<int> s = {1, 2, 3, 4, 5}; // copy list-initialization
s.append({6, 7, 8}); // list-initialization in function call
std::cout << "The vector now has " << s.c_arr().second << " ints:\n";
for (auto n : s.v)
std::cout << n << ' ';
std::cout << '\n';
std::cout << "Range-for over brace-init-list: \n";
for (int x : {-1, -2, -3}) // the rule for auto makes this ranged-for work
std::cout << x << ' ';
std::cout << '\n';
auto al = {10, 11, 12}; // special rule for auto
std::cout << "The list bound to auto has size() = " << al.size() << '\n';
auto la = al; // a shallow-copy of top-level proxy object
assert(la.begin() == al.begin()); // guaranteed: backing array is the same
std::initializer_list<int> il{-3, -2, -1};
assert(il.begin()[2] == -1); // note the replacement for absent operator[]
il = al; // shallow-copy
assert(il.begin() == al.begin()); // guaranteed
// templated_fn({1, 2, 3}); // compiler error! "{1, 2, 3}" is not an expression,
// it has no type, and so T cannot be deduced
templated_fn<std::initializer_list<int>>({1, 2, 3}); // OK
templated_fn<std::vector<int>>({1, 2, 3}); // also OK
}
출력:
constructed with a 5-element list
The vector now has 8 ints:
1 2 3 4 5 6 7 8
Range-for over brace-init-list:
-1 -2 -3
The list bound to auto has size() = 3
결함 보고 (Defect reports)
다음 동작 변경 결함 보고는 이전에 공개된 C++ 표준에 소급 적용되었어요.
| DR | 적용 대상 | 공개된 동작 | 올바른 동작 |
|---|---|---|---|
| LWG 2129 | C++11 | std::initializer_list에 명시적 특수화 또는 부분 특수화를 선언할 수 있었음 |
이 경우 프로그램의 형식이 잘못됨 |
| P3016R6 | C++11 | std::initializer_list에 불필요한 비멤버 begin 및 end 함수가 있었음 |
제거됨 |
같이 보기 (See also)
span (C++20) |
연속적인 객체 시퀀스에 대한 비소유 뷰 (클래스 템플릿) [편집] |
|---|---|
basic_string_view (C++17) |
읽기 전용 문자열 뷰 (클래스 템플릿) [편집] |