The code snippet under question involves returning a temporary std::string object from the foo() function and subsequently invoking bar() with the temporary's c_str() pointer. The concern stems from the assumption that the temporary gets destroyed before bar() executes.
However, this assumption is incorrect. According to the C language standard, a temporary object exists until the full expression in which it participates is complete. This concept is illustrated in the following code structure:
____________________ range of full expression bar( foo().c_str() ); ^^^^^ ^ | | birth funeral
In this example, the lifetime of the temporary returned by foo() extends from its creation at the point labeled "birth" to its destruction at "funeral." This destruction occurs after the call to bar(), not before as initially thought.
The precise rule states that a temporary object is destroyed when the full-expression that lexically contains the rvalue (right-hand side expression) responsible for creating it finishes evaluating. In the given code, this full-expression is the function call itself, bar( foo().c_str() ). Therefore, the temporary object continues to exist until this call completes, ensuring that bar() can access its c_str() pointer.
The above is the detailed content of How Long Do Temporary C Strings Live?. For more information, please follow other related articles on the PHP Chinese website!