Why Does Calling std::string.c_str() on a Returned String Fail?
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>
As you might expect, getString() returns a copy of its local string, seemingly keeping it alive in main(). However, the code unexpectedly prints garbage. This raises the question: when and why is the returned string destroyed?
The answer lies in the nature of temporaries in C . getString() returns a temporary std::string that is created within the function and is destroyed upon completion of the statement in which it is returned. This means that by the time cStr points to the string's underlying character array, the temporary has already been destroyed, and cStr becomes a dangling pointer, leading to undefined behavior.
To resolve this issue, the returned temporary can be bound to a named variable or reference, thereby extending its lifetime until the reference's scope ends:
<code class="cpp">std::string s1 = getString(); // s1 is initialized with a copy of the temporary auto& s2 = getString(); // s2 binds to the temporary by reference</code>
Alternatively, the pointer to the underlying character array can be used before the temporary is destroyed:
<code class="cpp">std::cout << getString().c_str() << std::endl; // Temporary is destroyed after the expression completes</code>
The above is the detailed content of ## Why Does Calling `std::string.c_str()` on a Returned String Lead to Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!