Is sharing data with initializer list out-scoped valid in standard?

Viewed 52

lst2 = lst Copying or assigning an initializer_list does not copy the elements in the list. After the copy, the original and the copy share the elements.

According to C++ Primer Table 6.1, assign one initializer list will share the data, but what if the initializer list share with an other out-scoped, for example, the code below is a part of a function

std::initializer_list<int> lst1;
{
    std::initializer_list<int> lst2 = {1, 2, 3};
    lst1 = lst2;
}

it seems initializer lists may share the literal's data, but what is the lifetime of the array literal specified in the standard? is this code safe?

1 Answers

This code does not seem valid. Here is some relevant extract from cppreference

The underlying array is a temporary array of type const T[N], in which each element is copy-initialized (except that narrowing conversions are invalid) from the corresponding element of the original initializer list. The lifetime of the underlying array is the same as any other temporary object, except that initializing an initializer_list object from the array extends the lifetime of the array exactly like binding a reference to a temporary (with the same exceptions, such as for initializing a non-static class member).

After you exit your inner scope, the temporary underlying array is going to be destroyed - as lifetime of inner lst2 ends - and lst1 from enclosing scope will end up with dangling pointers.

Related