Home > Article > Backend Development > Why Does Binding a Temporary Object to a Constant Reference Extend its Lifetime in C ?
In C , assigning a temporary object to a constant reference is a common operation that may initially raise questions about the lifetime of the temporary.
Question:
Why is the following code valid and does not result in a compiler error?
<code class="cpp">string foo() { return string("123"); } int main() { const string& val = foo(); printf("%s\n", val.c_str()); return 0; }</code>
Answer:
C explicitly defines that binding a temporary object to a constant stack-based reference extends the lifetime of the temporary to match that of the reference. In this scenario, the temporary returned by foo() lives until the end of the main() function.
Explanation:
Note:
The above is the detailed content of Why Does Binding a Temporary Object to a Constant Reference Extend its Lifetime in C ?. For more information, please follow other related articles on the PHP Chinese website!