在临时字符串上调用 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中文网其他相关文章!