Search code examples
c++stdstd-pair

Initializer list inside std::pair


This code:

#include <iostream>
#include <string>

std::pair<std::initializer_list<std::string>, int> groups{ { "A", "B" }, 0 };

int main()
{
    for (const auto& i : groups.first)
    {
        std::cout << i << '\n';
    }
    return 0;
}

compiles but returns segfault. Why?

Tested on gcc 8.3.0 and on online compilers.


Solution

  • std::initializer_list is not meant to be stored, it is just meant for ... well initialization. Internally it just stores a pointer to the first element and the size. In your code the std::string objects are temporaries and the initializer_list neither takes ownership of them, neither extends their life, neither copies them (because it's not a container) so they go out of scope immediately after creation, but your initializer_list still holds a pointer to them. That is why you get segmentation fault.

    For storing you should use a container, like std::vector or std::array.