9

What is supposed to happen in the following case:

int functionA() {
    return 25;
}

void functionB(const int& ref) {
    cout << ref << endl;
}

void start() {
    functionB(functionA());
}

When compiling this example, it outputs the correct value 25. How does this work? Should'nt the referenced return value on the stack be deleted (removed from the stack) when using only a reference to it, or is the behaviour undefined?

maxdev
  • 2,491
  • 1
  • 25
  • 50

2 Answers2

10

This "works" because of const int& ref - when a reference is const (guarantees that you don't want to change it), the compiler will produce a temporary object in the calling code (start in your case), and then pass the reference to that.

If you remove const it will fail to compile because functionA's result can't be turned into a reference.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • Compiler could produce a temporary object for non-const reference as well. Also, there is no strict guarantees, const object can be changed in bad code. I suppose it's rather an ideological restriction (as well as 'const' paradigm). – matreshkin Feb 01 '19 at 07:57
  • @matreshkin: The compiler can't pass a temporary object to a non-const reference. And that object CAN be changed within the code in the called function if you mess around with const-cast or similar. But the compiler won't allow a non-const reference to be a temporary object, which is the key for this question. If you have a non-const reference, the compiler will need something that remains after the call, because it expects you WANT to change it, and see the changed value - and a temporary object that disappears at the end of the call is useless if you want that. – Mats Petersson Feb 01 '19 at 08:11
9

There is no "return value on the stack" (let alone a "stack"): functionA returns an int by value, so the expression functionA() is simply a temporary value of type int. This value binds to the constant reference in functionB, and since its lifetime is that of the full expression, everything is fine.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084