返回对本地或临时变量的引用

cpx*_*cpx 41 c++

看下面的代码.我知道它不返回局部变量的地址,但为什么它仍然有效并将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不是其值.

  • 当他在main()中打印时,它会出现. (3认同)
  • @San:现在,@ Dave18编辑了这个问题. (2认同)