1

I am wondering what happens when you return int&. Lets jump to the example. I have a simple class Foobar storing one int. Lets have a look at this function:

Foobar showObjectsValue() {
    Foobar b(50);
    return b;
}

It returns copy of a local object so when I call this function I actually get some data instead of some trash. But when I do something like this:

Foobar& showObjectsValue() {
    Foobar b(50);
    return b;
}

It returns garbage because after we exit scope of the "showObjectsValue()" object "b" gets popped from the memory stack and we return reference to this popped object (correct me if I am wrong). But I don't know what is happening in case of returning int instead of object.

This function:

int& showIntegerValue() {
    int i = 50;
    return i;
}

and this function:

int showIntegerValue() {
    int i = 50;
    return i;
}

return the same value, both give me int = 50. So can someone explain what actually is going on in case of returning reference to local integer and local object?

hdw3
  • 871
  • 10
  • 28

1 Answers1

1

So can someone explain what actually is going on in case of returning reference to local integer and local object?

Integers are objects. Trying to access an alias to a destroyed object is undefined behavior. Don't expect anything from it. Your compiler should even give you a warning about this:

main.cpp:4:9: warning: reference to local variable 'i' returned [-Wreturn-local-addr]
     int i = 50;

In the end, when you're dealing with undefined behavior, just because you see something doesn't mean it is expected. To further prove this point, trying to run this code with GCC results in the warning above and a segmentation fault.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88