简体   繁体   English

编译器遇到return语句怎么办?

[英]What does the compiler do when encountering a return statement?

I have this code:-我有这个代码:-

int i;
class A
{
public:
    ~A()
    {
        i = 10;
    }
};

int& foo()
{
    i = 3;
    A ob;
    return i;
}

int main()
{
    cout << "i = " << foo() << endl; //call to foo
    return 0;
}

I'm confused about the order in which the compiler executes this code after encountering the return i statement.我对编译器在遇到 return i 语句后执行此代码的顺序感到困惑。 My guess: A variable of the caller(main) is made(say K) and a reference to it is passed to foo(), when the return statement is encountered, the compiler copies the value of the return statement into K, in this case the address of i, as a reference is being returned.我的猜测:调用者(main)的一个变量被创建(比如K)并将对它的引用传递给foo(),当遇到return语句时,编译器将return语句的值复制到K中,在此case i 的地址,作为引用被返回。 Then it jumps to the end of foo() and the destructor for class object ob is called which changes the value of i to 10. This is followed by the removal of foo() and all its variables(including the reference to K passed to foo) from the call stack and the control is returned to main where K replaces the call to foo() and the cout is implemented.然后它跳转到 foo() 的末尾并调用类对象 ob 的析构函数,将 i 的值更改为 10。接下来是删除 foo() 及其所有变量(包括对 K 的引用传递给foo) 并且控制返回到 main,其中 K 替换了对 foo() 的调用并实现了 cout。 Is this the correct order of actions taken by the compiler ?这是编译器采取的正确操作顺序吗?

I searched extensively for what happens in memory when a return is called and this was the best result, though it is for C#.我广泛搜索了调用 return 时内存中发生的情况, 是最好的结果,尽管它适用于 C#。

The function foo is in scope any place inside this source file, so there's no problem calling it.函数foo在此源文件中的任何位置都在作用域内,因此调用它没有问题。

As for the reference it's returning, i is a file scope variable and thus has static storage duration, which means its lifetime is the life of the program.至于它返回的引用, i是一个文件范围变量,因此具有静态存储持续时间,这意味着它的生命周期就是程序的生命周期。 This means you're allowed to return a reference to it from foo .这意味着您可以从foo返回对它的引用。

Had you attempted to return a reference to a local variable like this:您是否尝试过像这样返回对局部变量的引用:

int& foo()
{
    int x = 3;
    return x;
}

That would invokes undefined behavior since the variable no longer exists after the function exits.这将调用未定义的行为,因为在函数退出后变量不再存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM