Lifetime of a Braced-Init-List Return Value
In C , returning a braced-init-list from a function raises questions about the lifetime of the initializer_list and its underlying array.
Problem Outline
Previous analysis suggests that GCC incorrectly terminates the initializer_list array before the end of the return expression, while Clang incorrectly preserves objects without ever destructing them.
Standardese Interpretation
According to the C 11 standard, a return statement with a braced-init-list initializes the return value through copy-list-initialization. If the return type is a specialization of std::initializer_list, an initializer_list object is constructed and initialized from the specified list.
Array Lifetime
The constructed initializer_list stores a reference to an array of elements initialized from the initializer list. The array's lifetime is defined to be the same as the initializer_list object. This means that in the return statement, the underlying array is initialized from the braced-init-list and has a lifetime extending into the calling scope.
Correct Implementation
Therefore, the expected behavior is that the initializer_list's array should persist into the calling function, allowing for its further use or binding to a named reference. However, GCC's current implementation prematurely deallocates the array, violating this expectation.
Additional Clarifications
The above is the detailed content of What is the Lifetime of a Braced-Init-List Returned from a C Function?. For more information, please follow other related articles on the PHP Chinese website!