C++/STL

[C++ 11] std::initializer_list

sseram 2023. 11. 19. 15:10
반응형

공식 문서는 아래

 

https://en.cppreference.com/w/cpp/utility/initializer_list

 

std::initializer_list - cppreference.com

(not to be confused with member initializer list) template< class T > class initializer_list; (since C++11) An object of type std::initializer_list is a lightweight proxy object that provides access to an array of objects of type const T. A std::initialize

en.cppreference.com

 

const T 라는 객체의 배열에 access 할 수 있는 가벼운 proxy object. 라고 한다.

 

 


 

초기화를 할 때  { }  를 사용한다는 점이 가장 특이한 점이 아닐까 싶다.

 

int main()
{
	std::initializer_list<int> ili = { 1,2,3 };

	return 0;
}

 

이런 식으로.

 

즉, 우리가 '{ }' 이런 식으로 무언가를 선언한다면, 그 변수는 기본적으로 initializer_list 형태로 생성이 된다고 생각하면 된다.

이렇게 만들어진 initializer_list 에는 being(), end(), size() 등 array와 같은 형태의 구조체에서 기본적으로 가지고 있어야 할 모든 것들을 가지고 있다. 그러다 보니 이것들을 이용하여 여러 가지를 할 수 있다.

 

 

만약 vector<T> 를 만들게 된다면, initializer_list 객체를 넘겨 주면 바로 해당 값으로 vector를 초기화하고.

int main()
{
	std::vector<std::string> words1 = { "the", "frogurt", "is", "also", "cursed" };
}

 

 

 

 

단순 반목문에도 쉽게 사용이 가능하다.

int main()
{
	enum class color {
		red,
		green,
		blue
	};

	for (auto each_color : { color::red, color::green, color::blue });
	
	return 0;
}

 

 

 

 

 

다만 한 가지 사용 시 주의점이 있다.

 

우리는 변수를 초기화 할 때

int main()
{
	int aa(1);
	int bb{ 1 };
	int cc = 1;
	int dd = { 1 };
}

 

이런 식으로, () 를 사용할 수도 있고, 바로 = 으로 assign 시킬수도 있고, direct initialization 을 사용 할 수도 있다.

 

다만 저렇게 {} 쓰면.. 위에서는 initializer_list 형태로 생성된다고 하지 않던가?

 

 

그렇다.

다만 오해해서는 안 되는 것이, {} 로 초기화 하는 것도 엄연히 해당 타입의 한 초기화 방법이다.

int a(1) 이나, int a{1} 은 별 차이가 없다. 어차피 int 를 만들 때 1 이라는 값을 가지고 만드는 것이다.

 

다만 = {N} 를 하게 되는 순간, {N} 이라는 객체가 먼저 만들어 진 뒤 (기본적으로 initializer_list) 그 후 assign 되게 된다. 이 때 그 타입은 initializer_list 이다.

 

 

이 부분만 조심해서 편하게 사용하도록 하자!

 

 

 

 

* 잘못된 정보는 알려주시면 감사한 마음으로 수정하겠습니다.

반응형