C++C_str()的奇怪行为

C++ c_str() strange behavior

本文关键字:str C++C      更新时间:2023-10-16

我得到了以下程序:

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;
}

我希望看到s总是打印出"f",但下面是我得到的:

s = f
g() = g
s = g

我抓头发好几个小时了,但还是没弄清楚出了什么问题。

您的指针s在打印时无效,因为对f()的调用导致的临时std:string在此时被销毁(销毁发生在main函数第一行的完整表达式的和处)。

试试这个:

int main() {
  std::string f_string = f();
  const char *s = f_string.c_str();
  std::cout << "s = " << s << std::endl;
  std::cout << "g() = " << g() << std::endl;
  std::cout << "s = " << s << std::endl;
}

现在,当访问指针时,c_str所调用的字符串仍在作用域中时,它应该可以工作。