Lifetime of Temporaries Revisited
The provided code snippet showcases the intriguing behavior of temporary objects in C . Consider the following:
std::string foo() { std::string out = something...; return out; } void bar(const char* ccp) { // Do something with the string... } bar(foo().c_str());
The question arises: why is the "c_str()" pointer of the temporary returned by foo() still valid? Common sense might suggest that the temporary should be destroyed before bar() is called. However, this is not the case.
According to the C standard, a temporary object's lifetime extends until the evaluation of the full-expression that lexically contains the rvalue that created it is complete. This means that in the given code, the temporary object returned by foo() will stay alive until after the call to bar() is complete.
To visualize this concept, consider the following:
____________________ full-expression ranges from 'b' to last ')' bar(foo().c_str()); ^^^^^ ^ | | birth funeral
The temporary object is created when foo() is called (denoted as "birth"). It remains alive throughout the evaluation of the full-expression, which in this case is the function call bar(foo().c_str()). Once the function call is complete, the temporary object is destroyed (denoted as "funeral").
The above is the detailed content of Why Does a C Temporary String's `c_str()` Remain Valid After the Function Call?. For more information, please follow other related articles on the PHP Chinese website!