0

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.

Luca
  • 1,658
  • 4
  • 20
  • 41
  • 2
    The difference is in the 2nd example, `obj` still exists when you create `newObject`. In the first example, `obj` has stopped existing before you could create `newObject`. The function fully returns and clears it's variables before the result is assigned to `newObject`. – François Andrieux May 03 '17 at 13:59
  • No, because the object is destroyed *before* the function returns, while the can't be done before it does. – Jan Hudec May 03 '17 at 14:00
  • The other question is asking exactly the same thing - check it again. It asks why the reference can't be returned, and you're saying 'but if I *did* return it, what could I do with it'? – EML May 03 '17 at 14:18

1 Answers1

2

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055