This code compiles and executes. I know that we have undefined behaviour in the first case. But what happens exactly in the second case?
#include <string>
#include <iostream>
#include <cstdio>
std::string foo() {
return "HELLO";
}
void bar(const char *p) {
std::printf("%s
", 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 to c_str()
bar(foo().c_str());
return 0;
}
GCC output is in both cases "HELLO" but I think that's because it's not cleaning the raw memory.
In the second case when exactly is the temporary object destroyed?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…