从函数返回值如何工作?

编程入门 行业动态 更新时间:2024-10-13 20:13:54
本文介绍了从函数返回值如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我最近有一个严重的错误,我忘了在函数中返回一个值。问题是,即使没有什么返回它在Linux / Windows下工作正常,只有在Mac下崩溃。

I recently had a serious bug, where I forgot to return a value in a function. The problem was that even though nothing was returned it worked fine under Linux/Windows and only crashed under Mac. I discovered the bug when I turned on all compiler warnings.

这里是一个简单的例子:

So here is a simple example:

#include <iostream> class A{ public: A(int p1, int p2, int p3): v1(p1), v2(p2), v3(p3) { } int v1; int v2; int v3; }; A* getA(){ A* p = new A(1,2,3); // return p; } int main(){ A* a = getA(); std::cerr << "A: v1=" << a->v1 << " v2=" << a->v2 << " v3=" << a->v3 << std::endl; return 0; }

$ b <

My question is how can this work under Linux/Windows without crashing? How is the returning of values done on lower level?

推荐答案

在英特尔架构上,通常会返回简单的值(整数和指针)在 eax 寄存器中。该寄存器(除其他外)还用作在存储器中移动值时的临时存储器和在计算期间作为操作数。因此,该寄存器中的任何值都被视为返回值,在您的情况下,它确实是您想要返回的值。

On Intel architecture, simple values (integers and pointers) are usually returned in eax register. This register (among others) is also used as temporary storage when moving values in memory and as operand during calculations. So whatever value left in that register is treated as the return value, and in your case it turned out to be exactly what you wanted to be returned.

更多推荐

从函数返回值如何工作?

本文发布于:2023-11-26 02:30:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632295.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   返回值   工作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!