Local Variable Referencing Enigma: Returning Value or Address?
Many programmers may assume that returning references to local or temporary variables in functions is erroneous, resulting in undefined behavior. However, in certain situations, it may surprisingly succeed and modify the variable's value. Let's investigate this phenomenon with an illustrative code example:
#include <iostream> int& foo() { int i = 6; std::cout << &i << std::endl; // Prints the address of i before return return i; } int main() { int i = foo(); std::cout << i << std::endl; // Prints the value std::cout << &i << std::endl; // Prints the address of i after return }
If we execute this code, we observe curious behavior:
Explaining the Occurrence
This puzzling behavior can be attributed to a quirk in the way stack frames are handled in many implementations. When returning from a function, the stack frame is initially not immediately wiped.
In this example, the return type is int&, which means the function returns a reference to the address of i. The assignment int i = foo(); in main() stores the address of i in foo() in the variable i in main().
Simultaneously, the return instruction in foo() doesn't immediately release the stack frame. As a result, the variable i still exists in the stack memory, although it should have been destroyed. This allows i to be modified through its reference after returning.
Cautions and Implications
While this behavior may seem convenient, it is extremely dangerous and unreliable. Relying on the delayed stack frame destruction is a recipe for undefined behavior.
In well-defined code, you should ensure that local variables remain within the scope of their defining function and are promptly destroyed upon its termination. Failing to do so can lead to unpredictable consequences and errors.
The above is the detailed content of When Returning a Local Variable's Reference, Does It Return the Value or the Address (And Why Is This Dangerous)?. For more information, please follow other related articles on the PHP Chinese website!