Modern C++
주제 : std::Initializer_list
헤더 : <initializer_list>
설명 : initializer_list 타입의 객체는 배열 식의 접근이 가능한 경량화된 대용 객체(a lightweight proxy object)이다.
기존 C++03까지는 다음과 같은 4가지의 초기화 방법을 제공하였다.
예1 괄호) std::string s("apple"); 예2 =) std::string s = "apple"; int n = 0; 예3 {}) int arr[4] = {0,1,2,3}; struct tm today = {0}; 예4 생성자) struct S { int x; S(): x(0) {} }
기존 초기화의 문제점은 동적 배열의 초기화 방법이 없다는 것이었고, 초기화의 방법이 다소 복잡하단 점이었다.
C++11부터는 일관적이고 간결화된 초기화를 제공하기 위해 initializer_list를 이용하는 범용 균등 초기화(universal and uniform initialization)가 있다.
예1) std::string s{"apple"}; Point p{0,0}; 예2) std::string s1{s}; int n{0}; 예3) int *a = new int[4]{0,1,2,3}; 예4) std::vector v{"apple", "banana", "cherry"}; 예5) struct S { int x; S(): x{0} {} }; 예6) int* ptr{}; int *pArray[10]{};
또한, 이를 이용하면 축소 변환시 오류가 나기 때문에 좀 더 안전한 프로그래밍이 가능하다.
그리고, 클래스에서 생성자를 만들 때 initializer_list를 매개변수로 받을 수 있다. 이를 매개변수로 받으면 {}로 감싸진 객체를 받을 수 있다.
//예시 UnsortedArrayList::UnsortedArrayList(std::initializer_list<int> ilst) : mCapacity{ ilst.size() }, mList{ new int[mCapacity] } { for (auto item : ilst) { PushBack(item); } } //UnsortedArrayList list( { 1, 2, 3, 4, 5 } );와 같이 사용 가능 //혹은 UnsortedArrayList list = { 1, 2, 3, 4, 5 };
'Outdated > Library' 카테고리의 다른 글
[Modern C++] Smart Pointer - std::unique_ptr (0) | 2018.01.09 |
---|---|
[Modern C++ 14] Smart Pointer - std::weak_ptr (0) | 2018.01.04 |
[Modern C++ 14] Smart Pointer - std::shared_ptr (0) | 2018.01.02 |