Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a C++ compiler do with this initializer list?

When using an initializer list such as this:

for (int i : {3, 1, 6, 4})
{
    std::cout << "i=" << i << std::endl;
}

The ouput is in the same order, 3, 1, 6, and finally 4. So I know the compiler must be using something similar to std::vector<int> and not std::set<int>.

Is this guaranteed? Where can I find the docs that explain how the compiler must interpret {3, 1, 6, 4}.

like image 352
Stéphane Avatar asked Dec 06 '22 12:12

Stéphane


2 Answers

You are creating an instance of std::initializer_list<int>. See http://en.cppreference.com/w/cpp/utility/initializer_list for details.

From that page:

An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T.

The output order is guaranteed. However, that's not because the compiler creates a std::vector<int>. It is guaranteed because there is an array of ints underneath the initializer_list.

like image 103
R Sahu Avatar answered Jan 03 '23 04:01

R Sahu


Your range based loop is using the braced-init-list as a range expression which constructs a temporary object of type std::initializer_list<int>. The order is guaranteed because the 8.5.4.5. paragraph of the n4140 draft / standard states (emphasis mine):

An object of type std::initializer_list<E> is constructed from an initializer list as if the implementation allocated a temporary array of N elements of type const E, where N is the number of elements in the initializer list.

like image 41
Ron Avatar answered Jan 03 '23 03:01

Ron