首页  >  文章  >  后端开发  >  ## 为什么在返回的字符串上调用 `std::string.c_str()` 会导致未定义的行为?

## 为什么在返回的字符串上调用 `std::string.c_str()` 会导致未定义的行为?

Linda Hamilton
Linda Hamilton原创
2024-10-25 11:29:02591浏览

## Why Does Calling `std::string.c_str()` on a Returned String Lead to Undefined Behavior?

为什么在返回的字符串上调用 std::string.c_str() 会失败?

考虑以下代码:

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

正如您所料,getString() 返回其本地字符串的副本,似乎使其在 main() 中保持活动状态。然而,代码意外地打印出垃圾信息。这就提出了一个问题:返回的字符串何时以及为何被销毁?

答案在于 C 中临时变量的本质。 getString() 返回一个临时 std::string,该临时 std::string 在函数内创建,并在返回它的语句完成后销毁。这意味着当 cStr 指向字符串的底层字符数组时,临时变量已经被销毁,并且 cStr 成为悬空指针,导致未定义的行为。

要解决此问题,可以将返回的临时变量绑定到命名变量或引用,从而延长其生命周期,直到引用的范围结束:

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

或者,可以在销毁临时变量之前使用指向基础字符数组的指针:

<code class="cpp">std::cout << getString().c_str() << std::endl; // Temporary is destroyed after the expression completes</code>

以上是## 为什么在返回的字符串上调用 `std::string.c_str()` 会导致未定义的行为?的详细内容。更多信息请关注PHP中文网其他相关文章!

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