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

以下是一些适合问答格式并准确描述文章内容的标题选项: **选项 1(短线和直接):** * **为什么在 Re 上调用 `std::string.c_str()`

Patricia Arquette
发布: 2024-10-25 09:23:02
原创
674 人浏览过

Here are a few title options that fit the question-answer format and accurately describe the article's content:

**Option 1 (Short & Direct):**

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

**Option 2 (M

为什么在返回字符串的函数上调用 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() 返回一个临时字符串,该字符串在 main() 中的表达式末尾被销毁。

因此,cStr 持有一个悬空指针,使用它可能会导致未定义的行为。为了避免这一问题,可以使用命名变量或引用来确保返回字符串的有效性。例如:

<code class="cpp">std::string returnedString = getString();
const char* cStr = returnedString.c_str();
std::cout << cStr << std::endl; // Safe</code>
登录后复制

或者,可以直接使用临时字符串而不将其分配给变量:

<code class="cpp">std::cout << getString().c_str() << std::endl; // Also safe</code>
登录后复制

以上是以下是一些适合问答格式并准确描述文章内容的标题选项: **选项 1(短线和直接):** * **为什么在 Re 上调用 `std::string.c_str()`的详细内容。更多信息请关注PHP中文网其他相关文章!

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