-2

只需运行这个程序并解释最后一行的输出为什么它打印“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;
}
4

1 回答 1

0

那是因为您依赖于“f().c_str()”生成的临时值。该值集不会在将来对您的 char 数组的调用中扩展,即 s 包含垃圾,因为它已变得悬空。此外,它不一定总是打印'g'。

于 2017-12-04T06:05:13.790 回答