Home >Backend Development >C++ >How do const references ensure the lifetime of temporary objects in C ?

How do const references ensure the lifetime of temporary objects in C ?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 13:58:30281browse

How do const references ensure the lifetime of temporary objects in C  ?

Returning Temporary Objects to Const References

In C , a reference bound to a temporary object on the stack extend the temporary's lifetime for the duration of the reference itself. This prevents dangling reference errors.

Consider the following example:

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

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

In this code, the string returned by foo() is a temporary object. However, when it is bound to the const reference val, the temporary's lifetime is extended until the end of the function main(). This allows val to safely access the contents of the temporary string.

The C standard specifically allows this behavior to avoid common dangling-reference errors. Without it, the temporary string in the example above would be destroyed at the end of the function foo(), causing val to point to an invalid memory location.

Important Note:

This feature applies only to stack-based references. It does not extend the lifetime of temporary objects that are members of objects or stored in other dynamic memory locations.

The above is the detailed content of How do const references ensure 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