【问题标题】:Please explain the output of below program [duplicate]请解释以下程序的输出[重复]
【发布时间】: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() 的输出都会失效。无论您将它用于哪个变量,都不应依赖先前的值。

标签: c++ c-str


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2014-09-07
    相关资源
    最近更新 更多