I've tried the following:
std::string* Member::GetName()
{
std::string name2 = "sdfsdfsd";
return &name2;
}
std::string* name;
Member m;
name = m.GetName();
std::cout << *name << std::endl;
and it "works", but shouldn't be name2 unavailable after GetName() is called? and my pointer points to nothing?
Edit:
Coming back after years with more exp. some already answered this question below.
Returning a local is bad!, you might get away with it, if the value on the stack didn't get overwritten, so often when you directly use it after returning a local you might get the correct values, but this is still undefined behaviour. Also not returning a const& also doesn't work, even now sometimes i think it binds the return value to a temporary as it does for const& parameters, but thats not the case for return types, the same goes for returning r-values refs. you can only return a copy and get it as const ref like this
std::string GetName();
const std::string& name = GetName();
this will bind it to a temporary therefore is valid check herb sutters gotw: https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ for const ref temporaries.
why does it even work?It did "work". Crashing would also "work", running on your computer and crashing on someone else's would also "work". That's what "undefined behavior" is all about.