看下面的代码.我知道它不返回局部变量的地址,但为什么它仍然有效并将imain()中的变量赋值为'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
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*tos 23
你真是幸运.从函数返回不会立即擦除刚刚退出的堆栈帧.
顺便说一下,你是怎么证实你有6回来的?表达式std::cout << &i ...打印地址而i不是其值.
| 归档时间: |
|
| 查看次数: |
10366 次 |
| 最近记录: |