What happens to the return value if I don't st

2020-02-06 02:26发布

In the small sample below:

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

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.

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++
2条回答
够拽才男人
2楼-- · 2020-02-06 03:06

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).

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.

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

查看更多
女痞
3楼-- · 2020-02-06 03:25

In general: when a function returns a non-void value and the value does not get stored anywhere, the value is destroyed.

Specifically: natural datatypes, like ints and doubles, or pointers, don't have an explicit destructor, so nothing really happens. The returned value simply gets ignored.

If a function returns a class instance, the class instance gets destroyed, which results in an invocation of the class's defined destructor, or a default destructor.

查看更多
登录 后发表回答