3
#include <iostream>
#include <initializer_list>
#include <vector>

auto const v = std::vector<std::initializer_list<int>>{ { 0, 1, 2 }, { 3, 4 } };

int main()
{
    for (auto const& l : v)
        for (auto const& i : l)
            std::cout << i << " ";
}

This code outputs garbage, e.g.: 13386064 0 -1305220240 32764 0 (under several different compilers).

If I change v to a std::vector<std::vector<int>>, or move the definition inside main, it prints 0 1 2 3 4 as expected.

Why?

user673679
  • 1,327
  • 1
  • 16
  • 35
  • You really should try to never use global variables in the first place... – Jesper Juhl Apr 30 '20 at 17:47
  • 6
    Because {0,1,2} is temporary array which is deleted when the full expression is ended. So your vector has shallow copy of initializer list as proxy object consisted of pointer to data and length of data, but there is no more data to be pointed. *The underlying array is not guaranteed to exist after the lifetime of the original initializer list object has ended.* From [reference](https://en.cppreference.com/w/cpp/utility/initializer_list) – rafix07 Apr 30 '20 at 17:48
  • Sounds plausible. I guess the "original initializer list" would be the one used in the vector constructor. – user673679 Apr 30 '20 at 18:09
  • @rafix07 When you have an answer, please post it _as such_ so it can undergo the usual peer review. That's how this Q&A site works. Thanks. – Asteroids With Wings Apr 30 '20 at 18:15
  • Does this answer your question? [lifetime of a std::initializer\_list return value](https://stackoverflow.com/questions/15286450/lifetime-of-a-stdinitializer-list-return-value) – L. F. May 01 '20 at 01:44

1 Answers1

0

Try add const before int

auto const v = std::vector<std::initializer_list<const int>>{ { 0, 1, 2 }, { 3, 4 } };
Simas Joneliunas
  • 2,890
  • 20
  • 28
  • 35