More on initializer lists in C++

Initializer lists in C++ allow us to intialize arrays/vectors and more using a simple syntax, for example

std::vector<std::string> v = { "one", "two", "three" };

This will create a vector with three values “one”, “two” and “three”.

This works because an intializer list (i.e. the { “one”, “two”, “three” } in this example, is actually a std::initializer_list type and the vector has an overload = operator which accepts such a type and then copies the values into the vector. So the { } syntax is really just syntactic sugar.

Here’s the same code but showing the explicit use of the type, i.e. we create a std::initializer_list

std::initializer_list<int> il = { 1, 2, 3 };
// which is the same as this, with an auto
auto il = { 1, 2, 3 };

Knowing, as we do, that the initializer list will in fact create a std::initializer_list, it’s obvious that this will come with a slight overhear in terms of creating a std::initializer_list, then when assigned to a vector/array or the likes, we need to loop through the items in the list and copy into the vector. Hence if out and out speed and member use is an issue, one might prefer not to use such syntax.

We can also use an initializer list with a single value, for example

auto i{ 3 };

and this resolves to an int type with the value 3.