此代码编译并执行.我知道在第一种情况下我们有未定义的行为.但在第二种情况下究竟发生了什么?
#include <string>
#include <iostream>
#include <cstdio>
std::string foo() {
return "HELLO";
}
void bar(const char *p) {
std::printf("%s\n", p);
}
int main() {
// FIRST CASE:
// I know this is bad, because after the assignment
// the variable returned by foo() is destroyed and we
// have a bad reference.
const std::string &s = foo();
bar(s.c_str());
// SECOND CASE:
// But what about that ? I don't know exactly if the
// object is alive after the call …Run Code Online (Sandbox Code Playgroud) c++ ×1