Outdated/Library

[Modern C++]Initializer_list

해달 2017. 11. 24. 00:58

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 };