Stéphane
Stéphane

Reputation: 20340

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

Upvotes: 3

Views: 379

Answers (2)

R Sahu
R Sahu

Reputation: 206567

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.

Upvotes: 9

Ron
Ron

Reputation: 15501

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.

Upvotes: 6

Related Questions