Calling std::string.c_str() on a Temporary String
In C , a temporary object is destroyed at the end of the full expression in which it was created. In the given code, the line const char* cStr = getString().c_str(); creates a temporary std::string object from the return value of getString(). However, this temporary is destroyed before the cStr pointer can use it.
To fix this, you can either store the temporary in a named variable or bind it to a const lvalue-reference or rvalue-reference. For example:
<code class="cpp">std::string s = getString(); // Extended lifetime const char* cStr1 = s.c_str(); std::cout << cStr1 << std::endl; // Safe const std::string& s2 = getString(); // Const lvalue-reference const char* cStr2 = s2.c_str(); std::cout << cStr2 << std::endl; // Safe</code>
Alternatively, you can use the pointer before the temporary gets destroyed:
<code class="cpp">std::cout << getString().c_str() << std::endl; // Temporary used immediately</code>
The above is the detailed content of Here are a few question-based titles that fit the content of your article: **Direct and Focused:** * **Why Does Calling `std::string.c_str()` on a Temporary String Lead to Undefined Behavior?** * **. For more information, please follow other related articles on the PHP Chinese website!