std::initializer_list<T> is introduced in C++11 to make initialization uniform in C++.

Before C++11 it was easy to initialize an array with with default elements like,

But there was no way no to initialize other containers like vector, list and map etc.

For example, there was no way to initialize a vector with default values in a single line before c++11. The only ways was create a vector and push elements in it i.e.

 

But in C++11 we can do this in a single line i.e.

It would have resulted in a compile time error before C++11. It’s possible in C++11 because of Uniform Initialization feature of c++11 i.e.  std::initializer_list<T>

std::initializer_list

We can create light weight object of std::initializer_list<T> that will refer to an array of elements of type T i.e.

So, where ever compiler see elements in braces i.e. {a, b, c} it creates a  std::initialzer_list<T>, where T is the type of elements in the list. Now, all containers i.e. vector & list etc. has a parameterized constructor that accepts this std::initializer_list<T> as an argument and insert them i.e.

Therefore we can directly initialize a vector or any other container with default elements  i.e.

Here compiler will automatically create a object of std::initialzer_list<T> and make it refer to {1,2,3,4,5} and as vector has a constructor that accepts this as an argument. Hence it will initialize the vector with all the elements in it.

Complete Example is as follows,

Output:

std::initialzer_list<T> and Narrowing

 std::initialzer_list<T> also detects the narrowing of data i.e. it will detect the narrowing i.e.

Complete Example is as follows,

Output:

Lifetime of elements in std::initialzer_list<T> is till the object which refers to it.

Click Here to Subscribe for more Articles / Tutorials like this.