On Tue, Oct 5, 2010 at 3:42 AM, Peter Kasting <pkasting@chromium.org> wrote:
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.
Thanks Darin and Peter. I left out an important detail: the full function signature .(I mentally used my standard way of writing such code.) #1 was "B foo() { return B();}" vs #2 was "const B& foo() { return m_b; }" I suspect that the the example code written to test it looked like this: B& foo() { return B();} PK