Home  >  Article  >  Backend Development  >  Why Does Binding a Temporary Object to a Constant Reference Extend its Lifetime in C ?

Why Does Binding a Temporary Object to a Constant Reference Extend its Lifetime in C ?

DDD
DDDOriginal
2024-11-02 17:03:02627browse

Why Does Binding a Temporary Object to a Constant Reference Extend its Lifetime in C  ?

Returning Temporary Objects and Binding to Constant References

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:

  • Temporary objects typically have a short lifespan, ending at the end of the expression they appear in.
  • However, C allows an exception for const references on the stack.
  • By binding a temporary to a const reference on the stack, the lifetime of the temporary is extended to match the lifetime of the reference.
  • This prevents dangling reference errors caused by references pointing to objects that have been destroyed.

Note:

  • This exception only applies to stack-based const references.
  • It does not apply to references that are members of objects.
  • For more details, refer to Herb Sutter's "GotW #88: A Candidate For the “Most Important const”."

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn