gpt4 book ai didi

c++ - C++临时变量生存期?

转载 作者:行者123 更新时间:2023-12-01 15:06:42 27 4
gpt4 key购买 nike

我知道这在C++中是有效的,因为std::string("xxx")的临时生存期一直到它出现的完整表达式的结尾。

printf("%s\n", std::string("xxx").c_str());

这也是有效的:

std::string f1() {
return std::string("xxx");
}

void g1() {
printf("%s\n", f1().c_str());
}

但这有效吗?如果没有,为什么?

const char* f2() {
return std::string("xxx").c_str();
}

void g2() {
printf("%s\n", f2());
// or: std::string x = f2(); // is this valid?
}

最佳答案

函数返回时,std::string内部的临时f2被销毁。 char*将悬挂。

编辑:响应评论,std::string x = f2()也无效。从悬空的指针初始化std::string仍然很不好。

关于c++ - C++临时变量生存期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59639271/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com