简体   繁体   中英

Passing return value of a function as reference

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM