Why Calling std::string.c_str() on a Function Returning a String Fails
Consider the following code:
<code class="cpp">std::string getString() { std::string str("hello"); return str; } int main() { const char* cStr = getString().c_str(); std::cout << cStr << std::endl; // Outputs garbage }</code>
Intuitively, one would expect the returned temporary string from getString() to remain valid in main()'s scope. However, this is incorrect.
The issue lies in the lifetime of temporary objects in C . A temporary object is destroyed at the end of the expression in which it's created, unless it's bound to a reference or used to initialize a named object. In this case, getString() returns a temporary string, which is destroyed at the end of the expression in main().
Consequently, cStr holds a dangling pointer, and using it can lead to undefined behavior. To avoid this problem, one can use a named variable or reference to ensure the validity of the returned string. For instance:
<code class="cpp">std::string returnedString = getString(); const char* cStr = returnedString.c_str(); std::cout << cStr << std::endl; // Safe</code>
Alternatively, the temporary string can be used directly without assigning it to a variable:
<code class="cpp">std::cout << getString().c_str() << std::endl; // Also safe</code>
The above is the detailed content of Here are a few title options that fit the question-answer format and accurately describe the article\'s content: **Option 1 (Short & Direct):** * **Why Does Calling `std::string.c_str()` on a Re. For more information, please follow other related articles on the PHP Chinese website!