【发布时间】:2017-12-04 05:34:09
【问题描述】:
只需运行这个程序并解释最后一行的输出为什么它打印“g”而不是“f”。在这里我的目的是知道为什么它显示以前的函数返回值?
#include <iostream>
#include <string>
std::string f() {
return "f";
}
std::string g() {
return "g";
}
int main() {
const char * s = f().c_str();
std::cout << "s = " << s << std::endl;
std::cout << "g() = " << g() << std::endl;
std::cout << "s = " << s << std::endl;
}
【问题讨论】:
-
每次调用 c_str() 的输出都会失效。无论您将它用于哪个变量,都不应依赖先前的值。