Re: dangling reference

From: Method Man (a_at_b.c)
Date: 10/15/04


Date: Thu, 14 Oct 2004 18:47:04 -0400


"Hans Van den Eynden" <onsbomma@hotmail.com> wrote in message
news:1c2f5137.0410141238.4cb7a4ab@posting.google.com...
> I thought that integers resized on the stack and that a value type was
> just defined in the scope of the function. And when the function
> returns the local variables were removed from the stack. But what is
> the explication of this code??
>
> int& dangling_reference();
>
> int main(int argc, char *argv[])
> {
> int a;
> a= dangling_reference();
> cout<<a<<endl;
> cin.get();
> }
>
>
>
> int& dangling_reference() {
> int x=3;
> return x;
> }

This is UB. If you are getting the correct result (printing "3"), then
you're just lucky. This probably occured because your program is small and
the contents of the memory address of 'x' are still intact. Regardless, you
should not *expect* your code to work.