On Mon, Oct 4, 2010 at 4:23 AM, Leandro Graciá Gil <leandrogracia@chromium.org> wrote:
In summary, looking at code like this
B& b = c->foo();
...
b.m();
If c->foo() returns a temporary ("return B();"), then it is safe.
Maybe I'm wrong, but are you completely sure about this one? I would say that the temporary object created in return B() will cease to exist as soon as it returns (just after the constructor finishes).
foo() is returning a temp by value. On the caller side, that value is copied to a (hidden) temp whose lifetime is the same as the lifetime of |b|, and then |b| is set to be a reference to that temp.
By contrast, if foo were returning a temp by reference, then the reference would be invalid on return because the (foo()-scoped) temp it referred to would be destroyed when foo() exited.
PK