lifetime of a std::initializer_list return value

std::initializer_list is not a container, don’t use it to pass values around and expect them to persist

DR 1290 changed the wording, you should also be aware of 1565 and 1599 which aren’t ready yet.

Then the return value’s array should also survive into the calling function, and it should be possible to preserve it by binding it to a named reference.

No, that doesn’t follow. The array’s lifetime doesn’t keep being extended along with the initializer_list. Consider:

struct A {
    const int& ref;
    A(const int& i = 0) : ref(i) { }
};

The reference i binds to the temporary int, and then the reference ref binds to it as well, but that doesn’t extend the lifetime of i, it still goes out of scope at the end of the constructor, leaving a dangling reference. You don’t extend the underlying temporary’s lifetime by binding another reference to it.

Your code might be safer if 1565 is approved and you make il a copy not a reference, but that issue is still open and doesn’t even have proposed wording, let alone implementation experience.

Even if your example is meant to work, the wording regarding lifetime of the underlying array is obviously still being improved and it will take a while for compilers to implement whatever final semantics are settled on.

Leave a Comment