返回对本地或临时变量的引用 [英] Returning a reference to a local or temporary variable

查看:194
本文介绍了返回对本地或临时变量的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看下面的代码。我知道它不返回局部变量的地址,但为什么它仍然工作,并分配变量 i 在main()到'6'?

Look at the code below. I know it doesn't return the address of local variable, but why does it still work and assign the variable i in main() to '6'? How does it only return the value if the variable was removed from stack memory?

#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
}


推荐答案

你很幸运。从函数返回不会立即擦除刚刚退出的堆栈框架。

You got lucky. Returning from the function doesn't immediately wipe the stack frame you just exited.

BTW,你怎么确认你有一个6回来?表达式 std :: cout<< & i ... 打印 i 的地址,而不是其值。

BTW, how did you confirm that you got a 6 back? The expression std::cout << &i ... prints the address of i, not its value.

这篇关于返回对本地或临时变量的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆