Home >Backend Development >C++ >Does the Lifetime of a `std::initializer_list` Return Value Extend into the Calling Function?
Question:
According to the C standard, when a function returns an initializer list, should its underlying array's lifetime extend into the calling function?
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:
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!