如果不在C ++中返回值,会发生什么? [英] What happens if you don't return a value in C++?

查看:180
本文介绍了如果不在C ++中返回值,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天,我发现自己写的代码如下:

Yesterday, I found myself writing code like this:

SomeStruct getSomeStruct()
{
    SomeStruct input;

    cin >> input.x;
    cin >> input.y;
}



当然忘记实际返回刚刚创建的结构体。奇怪的是,这个函数返回的结构中的值被初始化为零(当使用g ++编译时)。

Of course forgetting to actually return the struct I just created. Oddly enough, the values in the struct that was returned by this function got initialized to zero (when compiled using g++ that is). Is this just a coincidence or did another SomeStruct get created and initialized somewhere implicitly?

推荐答案


还有另一个SomeStruct是隐式创建和初始化的吗?

Did another SomeStruct get created and initialized somewhere implicitly?

想想结构如何返回。如果 x y 都是32位,则它太大,无法容纳在32位架构的寄存器中,这同样适用于64位架构上的64位值(@Denton Gentry的回答提到了如何返回更简单的值),因此它必须分配到某个地方。为此使用堆是浪费的,所以它必须在堆栈上分配。但它不能在你的 getSomeStruct 函数的栈框架上,因为在函数返回后它不再有效。

Think about how the struct is returned. If both x and y are 32 bits, it is too big to fit in a register on a 32-bit architecture, and the same applies to 64-bit values on a 64-bit architecture (@Denton Gentry's answer mentions how simpler values are returned), so it has to be allocated somewhere. It would be wasteful to use the heap for this, so it has to be allocated on the stack. But it cannot be on the stack frame of your getSomeStruct function, since that is not valid anymore after the function returns.

编译器而是调用者告诉被调用函数在哪里放置结果(这可能是在调用者的堆栈上的某处),通过传递被调用的函数一个隐藏的指针到分配给它的空间。因此,它被设置为零的地方在调用者上,而不是在您的 getSomeStruct 函数。

The compiler instead has the caller tells the called function where to put the result (which is probably somewhere on the stack of the caller), by passing the called function a hidden pointer to the space allocated to it. So, the place where it is being set to zero is on the caller, not on your getSomeStruct function.

还有一些优化,例如命名值返回优化,其中可以省略额外的副本。所以,如果你使用了缺少的 return ,结果将直接在调用者分配的空间上创建,而不是创建一个临时文件并复制它。

There are also optimizations like the "named value return optimization" where extra copies can be elided. So, had you used the missing return, the result would be created directly on the space allocated by the caller, instead of creating a temporary and copying it.

要知道更多关于发生了什么,你必须看看调用函数。正在初始化(为零)一个空 SomeStruct ,稍后您将分配 getSomeStruct 函数的返回值?还是它在做别的事?

To know more about what is happening, you have to look at the caller function. Is it initializing (to zero) an "empty" SomeStruct to which you later assign the return value of your getSomeStruct function? Or is it doing something else?

这篇关于如果不在C ++中返回值,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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