Re: Returning a reference from a function.
On Jul 14, 12:06 am, Juha Nieminen <nos...@thanks.invalid> wrote:
James Kanze wrote:
The reason the standard says it doesn't require a diagnostic is
because it's impossible to determine in all cases. The standard
doesn't have too many options: if it's an error (it is), then it
is either undefined behavior, or a diagnostic is required. And
since it is impossible for a compiler to generate the diagnostic
in every case...
When the compiler compiles a 'return' statement it has to know
what is being returned, naturally.
But it can't know whether that what is a reference to a local
variable or not.
The compiler also sees all the local variables and, if necessary,
destroys them (calls destructors, etc) alongside the 'return'.
Thus it would sound trivial for the compiler to check if the
returned reference is pointing to a local variable which is destroyed
before the function is exited. It doesn't make sense to return a
reference to something which is being destroyed in the very same
The compiler knows it is returning a reference. It doesn't
necessarily know to what. If it is binding the reference to a
local variable in the return statement, it can warn; many do.
But what about things like:
f( bool condition, int& x )
static int y = 42 ;
return condition ? x : y ;
g( bool condition )
int x = 3 ;
return f( condition, x ) ;
Whether the reference is bound to a local variable depends on
the value of condition, which the compiler cannot possibly know.
James Kanze (Gabi Software) email: email@example.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34