[webkit-dev] PSA: Don't try to hold onto temporaries with references
Mike Marchywka
marchywka at hotmail.com
Mon Oct 4 05:54:36 PDT 2010
________________________________
> Date: Mon, 4 Oct 2010 12:23:06 +0100
> From: leandrogracia at chromium.org
> To: levin at google.com
> CC: webkit-dev at lists.webkit.org
> Subject: Re: [webkit-dev] PSA: Don't try to hold onto temporaries with
> references
>
> 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). So you
> will be returning a reference to a temporary which, I think, no longer
> is valid. I made a quick test to be sure and the destructor of B is
> indeed called. Why is it safe?
>
ok, I avoided saying anything since I have yet to contrib code and
quite frankly don't have an authoritiative answer but I do recall
when I was learning cpp the compiler would warn if you even tried
to return a ref to a temp( maybe this is just msvc or you need to try
it with -Wall ). If the thing it points to is on the stack, and presumably
the stack gets popped on return, you would probably need to generate
some really odd code to save this reference once the thing for which
it is a synonym goes out of scope. If you are defending this as
safe it may be nice to show what kind of code the compiler generates
to keep this thing valid.
>
> _______________________________________________ webkit-dev mailing list
> webkit-dev at lists.webkit.org
> http://lists.webkit.org/mailman/listinfo.cgi/webkit-dev
More information about the webkit-dev
mailing list