[webkit-dev] PSA: Don't try to hold onto temporaries with references
pkasting at chromium.org
Mon Oct 4 09:42:53 PDT 2010
On Mon, Oct 4, 2010 at 4:23 AM, 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).
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.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the webkit-dev