Lifetime of Temporaries Revisited
The code snippet provided in the original question demonstrates a seemingly paradoxical behavior where the temporary string returned by foo() remains valid even after it has allegedly been destroyed upon entering bar().
Contrary to the assumption, the temporary object is not entirely destroyed when the function that created it completes. Instead, its lifetime extends until the entire expression that contains the temporary is fully evaluated.
To illustrate this concept, let's break down the code into its components:
According to the C language rules, the const char* temporary produced by foo().c_str() will persist until the full expression bar(foo().c_str()) is completely evaluated. This means that the pointer remains valid even after the execution of foo() has finished.
To visualize this behavior, imagine the following timeline:
|--------------------|-----------|-----------|-----------| | | birth | funeral | | | | ^^^ | ^^^^ | | |--------------------| | | | | | bar() | | | | | | | | |--------------------| | | | | | | | evaluated | | | | | bar() | |--------------------| | | | | | | foo() | | | | | | | |--------------------| | | |
The temporary objects (the string out and the const char* pointer) are created when the expression foo().c_str() is evaluated, and they persist until the entire expression bar(foo().c_str()) has been evaluated. This ensures that the pointer provided to bar() is still valid when the function attempts to access the string.
Therefore, it is correct to assume that the temporary returned by foo() will be destroyed after the call to bar() completes, as this marks the end of the full expression that contains the temporary.
The above is the detailed content of Why Does a Temporary String Remain Valid After the Function That Created It Returns?. For more information, please follow other related articles on the PHP Chinese website!