Home > Backend Development > C++ > body text

Why Do Const References Extend the Lifetime of Temporary Objects in C ?

Linda Hamilton
Release: 2024-10-26 16:04:03
Original
873 people have browsed it

Why Do Const References Extend the Lifetime of Temporary Objects in C  ?

Understanding Temporary Object Lifetime with Const References

Introduction:

In C , the lifetime of temporary objects typically extends only until the end of the expression in which they are created. However, an exception arises when temporary objects are bound to const references, extending their lifespan beyond the original scope.

Specific Inquiry:

Why does the following code compile and execute successfully, even though the string returned from the foo function is a temporary object?

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

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

Answer:

The C standard explicitly defines that binding a temporary object to a reference to const on the stack extends the lifetime of the temporary until the lifetime of the reference itself. Thus, in the provided code, the temporary string returned by foo() remains alive until the closing brace of the main function.

Mechanism:

This feature ensures that references to temporary objects do not become dangling references, which would result in undefined behavior. While the temporary object is bound to the const reference, its memory is effectively pinned, allowing the program to continue using it safely.

Limitations:

It's important to note that this lifetime extension only applies to stack-based references. In contrast, references that are members of objects do not prolong the lifetime of temporary objects.

Additional Information:

For a more detailed discussion on this topic, refer to GotW #88: A Candidate For the “Most Important const” by Herb Sutter.

The above is the detailed content of Why Do Const References Extend the Lifetime of Temporary Objects in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!