I know that this question has been asked several (million) times, but I can't understand what follows:
If I have a function like this one:
Object &function()
{
Object obj;
return obj;
}
and a client code that calls it:
Object newObject = function();
I'm returning obj by reference meaning and that is bad because that object is destroyed as soon as it goes out of scope (after the terminating brace). But I'm passing that local object to a new object at the call site so shouldn't I be safe? Shouldn't the object have been copied (by its copy constructor) when it's gone? I know that passing a pointer to alocal object is bad, since I'm passing (by value) the pointer's location that will point to garbage once the (local) pointer goes out of scope (the stack frame is gone), but why references? Isn't the code the same as:
Object &temp = obj;
Object newObject = temp;
? please explain.
EDIT the question above is not asking the same thing. I fully understand why I shouldn't return a pointer to a local, and why I souldn't return a reference to a local to initialize a reference at the call site. What I don't understand is why I can't use a reference to a local to initialize an object at the call site. I don't think it's so trivial.
No, as you said yourself, it is not safe.
This is true no matter what you do with the now-invalid reference to the now-destroyed object.
It's too late to copy it.