首页  >  文章  >  后端开发  >  以下是一些适合您文章内容的基于问题的标题: **直接且专注:** * **为什么在临时字符串上调用 `std::string.c_str()` 会导致未定义的行为?** * **

以下是一些适合您文章内容的基于问题的标题: **直接且专注:** * **为什么在临时字符串上调用 `std::string.c_str()` 会导致未定义的行为?** * **

DDD
DDD原创
2024-10-26 10:25:03439浏览

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

在临时字符串上调用 std::string.c_str()

在 C 中,临时对象在字符串末尾被销毁它被创建时的完整表达。在给定的代码中,行 const char* cStr = getString().c_str();根据 getString() 的返回值创建一个临时 std::string 对象。但是,这个临时变量在 cStr 指针可以使用它之前就被销毁了。

要解决此问题,您可以将临时变量存储在命名变量中,或者将其绑定到 const 左值引用或右值引用。例如:

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

或者,您可以在临时对象被销毁之前使用指针:

<code class="cpp">std::cout << getString().c_str() << std::endl;  // Temporary used immediately</code>

以上是以下是一些适合您文章内容的基于问题的标题: **直接且专注:** * **为什么在临时字符串上调用 `std::string.c_str()` 会导致未定义的行为?** * **的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn