0
int& fun(){
    int a = 10;
    cout << &a << endl;
    return a;
}
int main() {
    int& r = fun();
    cout << r << endl;
    cout << &r << endl;
    return 0;
}

outputs of the code above are:

0xbf8567b4
10
0xbf8567b4

and when i change int& r = fun(); to int r = fun();
the addresses differ, they become:

0xbfa831e4
10
0xbfa83210

why this happens?

and i have another question that why i still can get "10" printed, "r" is the reference of the local variable "a" in fun(), isn't it that the "a" variable gets destroyed and the reference "r" becomes referencing nothing when the function calling finishes?

any help will be greatly appreciated!

Edited by mike_2000_17: Fixed formatting

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by kevintse
0

A reference in C++ is another name of an object. The fun() function returns a reference to the local int variable called a. After int& r = fun(); r is another name of INEXISTENT object: local (automatic) variable a (int object in automatic atorage - usually stack) of fun does not exist after fun() call ended.
That's why you get different results: you are trying to print a contents of reused stack space where variable a lived.
Of course, it's a logical error in your code. Good compilers (VC++, for example) print warning message in that case (VC++: "warning C4172: returning address of local variable or temporary").

0

I tested this in eclipse and it did warn me.
But I can't understand why the INEXISTENT object still holds the value 10, and can still be passed either to int& a or int a?

I did another test with a my own class:

class Apple{
    string name;
public:
    Apple(string);
    string getName();
};
string Apple::getName(){
    return this->name;
}
Apple* fun(){
    Apple apple("HELLO");
    return &apple;
}
int main() {
    Apple* apple = fun();
    cout << apple->getName() << endl;
    return 0;
}

and this time i got nothing printed, why?

Edited by mike_2000_17: Fixed formatting

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.