Home >Backend Development >C++ >How Long Do C Temporaries Live and Why Does This Code Work?
Lifetime of Temporaries
In C , temporaries are created for various reasons, such as returning values from functions or evaluating expressions. Understanding the lifetime of temporaries is crucial for correct program behavior.
Consider the following code snippet:
std::string foo() { std::string out = something...; return out; } void bar(const char* ccp) { // do something with the string.. } bar(foo().c_str());
In this code, the temporary string created by foo() is referred to by a const char* pointer in the call to bar(). The question arises: why is this code valid?
The answer lies in the lifetime of the temporary. According to the C standard, a temporary object is destroyed when the full expression that lexically contains the rvalue that created the object is completely evaluated.
In the above code, the full expression is bar(foo().c_str()). The evaluation of this expression begins at ' (the open parenthesis) and ends at the last ')' (the closing parenthesis). Within this expression, the temporary string is created by evaluating foo(), and the c_str() method is called on the temporary.
Therefore, the temporary string comes into existence at the beginning of the full expression and is destroyed when the expression is fully evaluated, which is after the call to bar(). This explains why the const char* pointer in bar() still refers to a valid string.
In summary, the temporary returned by foo() is only destroyed once the complete expression containing it has been evaluated, ensuring that the pointer returned by foo().c_str() remains valid throughout the call to bar().
The above is the detailed content of How Long Do C Temporaries Live and Why Does This Code Work?. For more information, please follow other related articles on the PHP Chinese website!