Re: Returning Refs
On Apr 1, 6:18 pm, "Jim Langston" <tazmas...@rocketmail.com> wrote:
"Victor Bazarov" <v.Abaza...@comAcast.net> wrote in message
news:yvqdnS_pT4j-WJLbnZ2dnUVZ_v6tnZ2d@comcast.com...
Jim Langston wrote:
<EvilOld...@googlemail.com> wrote in message
news:1175349463.536538.36070@y80g2000hsf.googlegroups.com...
const Thing &operator++(int)
{
Thing temp = *this;
operator++();
return temp;
}
Is this code robust ?
No. You are returning a reference to a temporary item.
Just a clarification here... 'Temporary' has a very specific
meaning in C++. 'temp' here is an *automatic* object, and not
a C++ temporary. While it *is* temporary (hell, the whole
program is temporary since it only lasts while in computer's
memory), it has different lifetime than a _true temporary_.
Since a temporary is always used (though it may be optimized away) to
return a result from a function call, the original response could have
been:
"No. You are returning a temporary bound to a reference to a local
object."
The trouble with binding a temporary to a reference (when the
referenced object is local) is simply this: as soon as the local
object goes out of scope - the lifetime of the temporary ends as well.
Therefore (and as others have already noted) the actual object as
returned to the caller is no longer a valid object.
Greg