Home  >  Article  >  Backend Development  >  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?** * **

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?** * **

DDD
DDDOriginal
2024-10-26 10:25:03439browse

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?**
* **How to Safely Use `std::string.c_str()` with Temporary

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!

Statement:
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