从函数返回值是如何工作的?

How does returning values from a function work?(从函数返回值是如何工作的?)
本文介绍了从函数返回值是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了一个严重的错误,我忘记在函数中返回一个值.问题是,即使没有返回任何内容,它在 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;
}

我的问题是如何在 Linux/Windows 下运行而不会崩溃?底层的值返回是怎么做的?

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

推荐答案

在 Intel 架构上,简单的值(整数和指针)通常在 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.

这篇关于从函数返回值是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)