What are the differences between these returning addresses of local functions?

I have the following functions (written in Visual C ++ 2005)

int &getInt_1()
{
    int a = 5;
    int &p = a;
    int p1 = p; // Line 1
    return p1;
}

int &getInt_2()
{
    int a = 5;
    int &p = a;
    return p;
}

As I already knew, both of these functions return the address of a local variable. If I am right, then I have the following questions:

  • What are the differences between the above features? Why getInt_1()does it receive a warning from the compiler ( "returning address of local variable"), but getInt_2()not?

  • What does it mean Line 1? After Line 1, p1also becomes a reference to a?

+1
source share
3 answers
  • getInt_1returns a reference to p1. getInt_2returns a link to a. Both are the same undefined behavior, do not do this. VC should give a warning to both.
  • No, you are just copying the value.
+3

1) undefined , - , . , MSVS.

2) , p1 . int p1 = a;

+1

In the first case, it is easy for the compiler to show that you are returning a link to a local variable; in the second case, it is more complicated, because it just has an arbitrary reference, which happens to be related to a local variable. This is probably why you get a warning in the first case, but not in the second.

And no, in the first case it p1is just normal int, not int&.

+1
source

All Articles