Home  >  Article  >  Backend Development  >  How Do Const References on the Stack Extend the Lifetime of Temporary Objects in C ?

How Do Const References on the Stack Extend the Lifetime of Temporary Objects in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 19:11:02980browse

How Do Const References on the Stack Extend the Lifetime of Temporary Objects in C  ?

Binding Temporary Objects to Const References

In C , binding a temporary object to a reference to const on the stack extends its lifetime to that of the reference itself. This exception to the rule that temporary objects typically expire at the end of the enclosing expression allows for more flexibility and safety in dealing with temporary objects.

Consider the following code:

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

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

Here, a temporary string object is returned from the foo() function. Typically, this temporary would cease to exist at the end of the full expression involving foo(). However, by binding it to the constant reference val, the temporary string's lifetime is prolonged until the closing curly brace.

This deviation from the usual temporary lifetime rules allows for safer code that avoids dangling references. In the example above, the temporary string bound to val is guaranteed to exist as long as val exists.

Note that this property only applies to references to const on the stack. It does not extend the lifetime of temporary objects referenced by member variables of objects.

For a more in-depth understanding, refer to Herb Sutter's GotW #88: A Candidate For the "Most Important const" available here: https://www.gotw.ca/publications/mill19.htm.

The above is the detailed content of How Do Const References on the Stack Extend the Lifetime of Temporary Objects 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