How to append a initializer_list returned from a function to another vector?

Viewed 160

I would like to append a initializer_list of objects returned from a function to another vector, ideally as a 1 liner like so:

int main()
{
    std::vector<int> integers(0);
    integers.reserve(8);
    integers.insert(integers.end(), generate_4_ints()); // vector size is now 4
    integers.insert(integers.end(), generate_4_ints()); // vector size is now 8
}

std::initializer_list<int> generate_4_ints()
{
    int first = 1, second = 2, third = 3, fourth = 4;
    return {first, second, third, fourth};
}

The only problem with the code above is that the values returned from generate_4_ints() lose their assigned value and instead return garbage, as if no copies were returned. I assume this is some peculiar behavior to do with initializer_list.

0 Answers
Related