【发布时间】:2011-02-14 05:09:14
【问题描述】:
看看下面的代码。我知道它不会返回局部变量的地址,但是为什么它仍然可以工作并将main()中的变量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
}
【问题讨论】:
-
你很幸运。不要这样做。
-
您可能会发现这很有用:stackoverflow.com/questions/6441218/…
-
我相信有些运气是因为 i 在 foo() 中没有改变(它允许编译器放置在文本或长期存在的地方而不是堆栈中)
-
从局部变量获取地址可能会阻止编译器/运行时为其使用寄存器。结果表现不佳。
标签: c++