[webkit-dev] PSA: Don't try to hold onto temporaries with references
Hans Wennborg
hans at chromium.org
Mon Oct 4 04:41:32 PDT 2010
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();
>> ...
>> 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).
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:
c->foo().m();
But not this:
B& b = c->foo();
// the temporary is gone now
b.m(); // trouble
Hans
More information about the webkit-dev
mailing list