You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中临时std::string的c_str()指针是否存在未定义行为?

临时std::string与c_str()指针有效性的问题

以下是相关代码:

#include <string>
#include <iostream>

void Print(const char* s) {
    std::cout << s << std::endl;
}

std::string GetString() {
    std::string ret;
    ret = "Is this defined behavior?";
    return ret;
}

int main() {
    Print(GetString().c_str());
}

这段代码属于定义行为,不会出现指针悬空的问题。

C++标准明确规定,表达式中的临时对象会在包含该表达式的完整表达式结束后才被销毁。在Print(GetString().c_str());这行代码中,GetString()返回的临时std::string对象,其生命周期会延续到整个Print函数调用表达式执行完毕之后。也就是说,当Print函数内部使用c_str()返回的指针时,对应的临时string对象仍然存在,指针指向的内存是完全有效的。

只有当Print函数执行完成、整个表达式结束后,这个临时string才会被销毁,此时指针才会失效,但此时已经不再需要使用该指针了。

内容的提问来源于stack exchange,提问作者David Carpenter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 09:42:31