[webkit-dev] PSA: Don't try to hold onto temporaries with references

David Levin levin at google.com
Mon Oct 4 12:52:45 PDT 2010

On Tue, Oct 5, 2010 at 3:42 AM, Peter Kasting <pkasting at chromium.org> wrote:

> 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();
>>>  ...
>>>  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();}"


#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();}

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.webkit.org/pipermail/webkit-dev/attachments/20101005/539c0824/attachment.html>

More information about the webkit-dev mailing list