Home > Backend Development > C++ > Why Does a C Temporary String's `c_str()` Remain Valid After the Function Call?

Why Does a C Temporary String's `c_str()` Remain Valid After the Function Call?

Mary-Kate Olsen
Release: 2024-12-16 18:57:21
Original
189 people have browsed it

Why Does a C   Temporary String's `c_str()` Remain Valid After the Function Call?

Lifetime of Temporaries Revisited

The provided code snippet showcases the intriguing behavior of temporary objects in C . Consider the following:

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

The question arises: why is the "c_str()" pointer of the temporary returned by foo() still valid? Common sense might suggest that the temporary should be destroyed before bar() is called. However, this is not the case.

According to the C standard, a temporary object's lifetime extends until the evaluation of the full-expression that lexically contains the rvalue that created it is complete. This means that in the given code, the temporary object returned by foo() will stay alive until after the call to bar() is complete.

To visualize this concept, consider the following:

____________________   full-expression ranges from 'b' to last ')'
bar(foo().c_str());
     ^^^^^          ^
       |            |
     birth       funeral
Copy after login

The temporary object is created when foo() is called (denoted as "birth"). It remains alive throughout the evaluation of the full-expression, which in this case is the function call bar(foo().c_str()). Once the function call is complete, the temporary object is destroyed (denoted as "funeral").

The above is the detailed content of Why Does a C Temporary String's `c_str()` Remain Valid After the Function Call?. 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