首页 > 后端开发 > C++ > 正文

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

Linda Hamilton
发布: 2024-10-25 11:29:02
原创
590 人浏览过

## 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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!