3
#include <iostream>
#include <initializer_list>
using X = std::initializer_list<int>;
int main()
{
    for (int i: (true? X{7, 8, 2, 3, 9}: X{5, 6, 7}))
        std::cout << i << ' ';
}

The expected output was

7 8 2 3 9

Instead, this code prints 5 uninitialized integers on the GCC compiler.

According to what I read about ranged for loops (https://en.cppreference.com/w/cpp/language/range-for), the ternary operator is supposed to return an initializer list rvalue, and then that rvalue is supposed to be bound to the range expression which is a universal reference. If so, then why does the initializer list seem to get deleted somewhere along the way? What's going on with these uninitialized values?

Right now I see that using an std::vector instead

#include <vector>
using X = std::vector<int>;

the expected output is shown. Why is that? What goes wrong with std::initializer_list and doesn't go wrong with std::vector?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
GT 77
  • 448
  • 5
  • 12

0 Answers0