如果我不将其存储在任何地方,返回值会怎样? [英] What happens to the return value if I don't store it anywhere?

查看:58
本文介绍了如果我不将其存储在任何地方,返回值会怎样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的小样本中:

#include<iostream>
using namespace std;

int z(){
    return 5 + 10; // returns 15
}

int main(){
    z(); // what happens to this return?
    cout << "Did not fail";
    return 0;
}

15会发生什么?我尝试在调试器中运行它,但在任何地方都找不到它。我认为这是因为它没有分配给它消失的任何东西,但我觉得那是错误的。

What happens to the 15? I tried running it in debugger but I can't find it anywhere. I assume that because it didn't get assigned to anything it just vanished but I feel like that's wrong.

今天我问了我的TA,他告诉我它存储在调用堆栈中,但是当我在调试器中查看它时,我发现不是。

I asked my TA about this today and he told me it's stored on the call stack but when I viewed it in debugger I see that it is not.

推荐答案

C ++标准强加了假设规则。该规则意味着,只要尊重所有副作用(系统其余部分可见的输入和输出,如写入文件或在屏幕上显示内容),C ++编译器就可以对程序执行任何操作。回到我的时髦的哲学评论,这意味着在C ++中,当一棵树掉到森林里时而且没有人可以听到它,它没有发出声音(但是可以)。

The C++ standard imposes the "as-if" rule. That rule means that a C++ compiler can do anything to a program as long as all side effects (inputs and outputs that are visible to the rest of the system, like writing to a file or showing stuff on the screen) are respected. Going back to my cheeky philosophical comment, this means that in C++, when a tree falls in the forest and no one is there to hear it, it doesn't have to make a sound (but it can).

您的程序在较高的层次上,由于您的函数不执行任何操作,因此编译器可能会或可能不会创建对它的调用,甚至可能将其从编译的二进制文件中删除。如果包含并调用它,则返回值将到达平台应用程序二进制接口指定的任何返回槽。在几乎每个x86_64系统上,这都是 rax 寄存器,用于获取整数返回值。返回值在那里,但永远不会被读取,并且在某些时候将被覆盖。

In the case of your program, at a high level, since your function does nothing, the compiler may or may not create a call to it, or could even remove it from the compiled binary. If it does include and call it, the return value will go to whatever return slot your platform's application binary interface specifies. On almost every x86_64 system, that will be the rax register for an integer return value. The return value is there but will never be read and will be overwritten at some point.

如果它是一个非平凡的对象而不是一个 int ,其析构函数将立即被调用。

If it was a non-trivial object instead of an int, its destructor would be invoked immediately.

这篇关于如果我不将其存储在任何地方,返回值会怎样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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