Home  >  Article  >  Backend Development  >  What is the Lifetime of a Braced-Init-List Returned from a C Function?

What is the Lifetime of a Braced-Init-List Returned from a C Function?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 18:29:22650browse

 What is the Lifetime of a Braced-Init-List Returned from a C   Function?

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

  • Returning a braced-init-list does not imply a copy-construction of the returned object. It simply uses copy-list-initialization to initialize the return value.
  • DR 1290 has revised the wording related to initializer_list lifetime, and DR 1565 and 1599 are also under consideration, potentially bringing further changes.
  • Binding an additional reference to the initializer_list does not extend the lifetime of its underlying array, similar to how a reference to a temporary object does not extend the temporary's lifetime.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn