[webkit-dev] PSA: Don't try to hold onto temporaries with references
hans at chromium.org
Mon Oct 4 05:05:26 PDT 2010
On Mon, Oct 4, 2010 at 12:41 PM, Hans Wennborg <hans at chromium.org> wrote:
> On Mon, Oct 4, 2010 at 12:23 PM, Leandro Graciá Gil
> <leandrogracia at chromium.org> wrote:
>>> In summary, looking at code like this
>>> B& b = c->foo();
>>> 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).
> Actually, the temporary object ceases to exist as soon as *the
> expression containing the call completes*, as Peter Kasting pointed
> out. So this should be ok:
> B b = c->foo(); // foo() returns a reference to a temporary, and the
> temporary is then copied to b, then destroyed
> And this too:
> But not this:
> B& b = c->foo();
> // the temporary is gone now
> b.m(); // trouble
I take it all back! I read that standards quote a bit too fast :) "A
temporary bound to the returned value in a function return statement
persists until the function exists". I suppose that says it all.
Leandro is right, I think.
More information about the webkit-dev