Passing the return value of the function as a reference

What should 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 displays the correct value of 25. How does it work? Should the excluded reference value on the stack be deleted (removed from the stack) when using only a reference to it or undefined behavior?

+7
c ++ stack pass-by-reference reference return-value
source share
2 answers

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

If you remove const , it will not be able to compile, because the result of functionA cannot be referenced.

+8
source share

There is no "return value on the stack" (not to mention the "stack"): functionA returns int by value, so the expression functionA() is just a temporary value of type int . This value is bound to a constant reference in functionB , and since its lifetime is a complete expression, everything is in order.

+8
source share

All Articles