Lifetime of Returned std::initializer_list Array
The lifetime of an std::initializer_list array returned from a function has sparked discussion regarding the behavior in different compilers. The question arises whether GCC's destruction of the array at the end of the return full-expression is correct.
Analysis of the Standard
According to C 11 §6.6.3/2, a return statement with a braced-init-list leads to the returned object or reference being copy-list-initialized from the initializer list. This process initializes a temporary initializer_list object and its underlying array storage from the initializer list, and then another initializer_list is initialized from the first.
The lifetime of the array, as defined in 8.5.4/6, matches the lifetime of the initializer_list object. This can be understood through an example where the initializer_list object and array have a full-expression lifetime for a std::vector initialized with a braced-init-list.
Return Value of a Braced-Init-List
When a bare list enclosed in braces is returned, copy-list-initialization is used. This is similar to the syntax nocopy X = { 3 }, which does not involve a copy and is identical to the example in 8.5.4/6 where the array's lifetime is extended.
Issues with GCC and Clang
However, there is a discrepancy in implementation between GCC and Clang. GCC destroys the array before returning, while Clang preserves a named initializer_list but never destroys the objects in the list.
Recommendation
It is advised to avoid using std::initializer_list to pass values around with the expectation of them persisting. Uncertainties in the standard and compiler implementations make it unreliable for preserving object lifetime.
The above is the detailed content of Is GCC\'s Destruction of a Returned `std::initializer_list` Array Correct?. For more information, please follow other related articles on the PHP Chinese website!