Home  >  Article  >  Backend Development  >  How Can I Extend the Lifetime of Temporary Objects in C Using Const References?

How Can I Extend the Lifetime of Temporary Objects in C Using Const References?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 19:45:02541browse

How Can I Extend the Lifetime of Temporary Objects in C   Using Const References?

Binding Temporary Objects to Const References

In C , temporary objects typically expire at the end of the expression in which they appear, potentially leading to dangling references. However, the language offers a unique feature that allows extending the lifetime of temporaries when bound to const references.

The following code demonstrates this concept:

<code class="cpp">string foo() {
  return string("123");
}

int main() {
  const string& val = foo();
  printf("%s\n", val.c_str());
  return 0;
}</code>

Despite foo() returning a temporary string, the assignment to the const reference val prolongs the temporary's lifetime until the reference itself expires. This is intended behavior as per the C standard, ensuring that val always points to a valid object.

However, it's important to note that this exception only applies to stack-based references. References that are members of objects do not extend the lifetime of their bound temporary objects. For more details on this feature, refer to Herb Sutter's "GotW #88: A Candidate For the “Most Important const”."

The above is the detailed content of How Can I Extend the Lifetime of Temporary Objects in C Using Const References?. 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