Home > Backend Development > C++ > How Long Do C Temporaries Live and Why Does This Code Work?

How Long Do C Temporaries Live and Why Does This Code Work?

Susan Sarandon
Release: 2024-12-15 04:42:11
Original
267 people have browsed it

How Long Do C   Temporaries Live and Why Does This Code Work?

Lifetime of Temporaries

In C , temporaries are created for various reasons, such as returning values from functions or evaluating expressions. Understanding the lifetime of temporaries is crucial for correct program behavior.

Consider the following code snippet:

std::string foo() {
  std::string out = something...;
  return out;
}

void bar(const char* ccp) {
  // do something with the string..
}

bar(foo().c_str());
Copy after login

In this code, the temporary string created by foo() is referred to by a const char* pointer in the call to bar(). The question arises: why is this code valid?

The answer lies in the lifetime of the temporary. According to the C standard, a temporary object is destroyed when the full expression that lexically contains the rvalue that created the object is completely evaluated.

In the above code, the full expression is bar(foo().c_str()). The evaluation of this expression begins at ' (the open parenthesis) and ends at the last ')' (the closing parenthesis). Within this expression, the temporary string is created by evaluating foo(), and the c_str() method is called on the temporary.

Therefore, the temporary string comes into existence at the beginning of the full expression and is destroyed when the expression is fully evaluated, which is after the call to bar(). This explains why the const char* pointer in bar() still refers to a valid string.

In summary, the temporary returned by foo() is only destroyed once the complete expression containing it has been evaluated, ensuring that the pointer returned by foo().c_str() remains valid throughout the call to bar().

The above is the detailed content of How Long Do C Temporaries Live and Why Does This Code Work?. 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