I'm a Java programmer, I'm new to C++ and recently I've been writing some C++ code. I'm a bit confused by C++ objects' lifetime (in Java there is garbage collection and I don't have to worry about this issue).
Here is my question.
Suppose I have a function f()
char *f() {
string a = "Hello";
return a.c_str();
}
Is this code valid? What confuses me is: what is the lifetime of the string a
declared inside of f
, will it be garbage-collected when f
returns? Can I rely on the returned a.c_str()
to be correct outside f
?