看一下下面的代码。我知道它没有返回局部变量的地址,但是为什么它仍然能够运行并将主函数中的变量i赋值为6?如果该变量已经从堆栈内存中移除,它是如何仅仅返回其值的呢?
#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
}