James Kanze
10/14/2008 10:13:00 PM
On Oct 14, 8:35 pm, casul <olivier.gr...@gmail.com> wrote:
> Given the following code :
> char const & identity( char const &c ) { return c; }
> char const & f( ) { return identity('A'); }
> char const & g( ) { return 'A'; }
> Of course, the compiler complains of function 'g' returning a
> reference to a temporary. But the compiler (I used gcc 4.2.x)
> doesn't say anything regarding the function 'f'.
How could it? Suppose that identity() and f() where in
different translation units. How could the compiler know that f
is in fact returning a reference to it's temporary?
> I know that temporaries bound to constant references have a
> life span that extends to the expression in which the function
> call where the bounding took place is evaluated.
Then you know something that is completely wrong. A temporary
has a lifetime until the end of the full expression in which it
appears. *IF* the temporary is used to initialize a reference,
it's lifetime is extended to match that of the reference (except
that a temporary bound to a reference being returned explicitly
doesn't have its lifetime extended). But whether the temporary
is bound to some other reference or not has no effect on its
lifetime.
> Now given that, is the fact of returning in turn the constant
> reference returned by 'identity' considered to be part of the
> expression in which 'identity' is evaluated, ie the expression
> is
> return identity('A');
> or does the evaluated expression just consist of the function
> call 'identity', ie:
> identity('A');
> ?
The temporary 'A' is used to initialize the reference which is
an argument of identity. The lifetime of that reference ends on
return from identity, which is *before* the end of the full
expression. So the lifetime of the temporary is at the end of
the full expression. (Actually, there's a slight extension
here; if the temporary were used to directly initialize the
return value, it's lifetime would be extended until the return
value was constructed. That's not the case here, however.)
> I would have said the first case. But I'm not sure. I guess
> the main question is: does a call to 'f' yield undefined
> behaviour ?
Of course.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34