Home > Backend Development > C++ > body text

Does the Lifetime of a `std::initializer_list` Return Value Extend into the Calling Function?

Patricia Arquette
Release: 2024-10-28 22:44:02
Original
996 people have browsed it

Does the Lifetime of a `std::initializer_list` Return Value Extend into the Calling Function?

Lifetime of a std::initializer_list Return Value

Question:

According to the C standard, when a function returns an initializer list, should its underlying array's lifetime extend into the calling function?

Analysis

The C standard states that a std::initializer_list object's lifetime is the same as the object it initializes. When a function returns an initializer list, it initializes the return value object. However, there are two instances of the initializer list involved: the one in the function and the one in the calling code.

The example in the standard suggests that the array's lifetime extends to the copied-to object, which would imply that the return value's array should also survive in the calling function. However, this is not the case in practice.

Answer:

Currently, the behavior of the lifetime of an std::initializer_list return value is not clearly defined in the C standard. Different compilers implement it differently:

  • GCC incorrectly destroys the array before returning, while preserving named initializer lists.
  • Clang correctly processes the example from the standard, but never destroys objects in the list. This would lead to a memory leak.
  • ICC does not support initializer lists at all.

In conclusion, it is not currently possible to rely on the lifetime of a std::initializer_list return value extending into the calling function. Avoid using std::initializer_list to pass values around, as it can lead to unexpected behavior.

Additional Notes:

DR 1290 modified the wording of the standard, and DRs 1565 and 1599, which are still open, address related issues. However, the semantics are still being defined, and it will take time for compilers to implement the final changes.

The above is the detailed content of Does the Lifetime of a `std::initializer_list` Return Value Extend into the Calling Function?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!