c++ - 关于在 C/C++/Assembly 中返回多个值

标签 c++ assembly optimization x86 return-value

我读过一些关于返回多个值的问题,例如 What is the reason behind having only one return value in C++ and Java? , Returning multiple values from a C++ functionWhy do most programming languages only support returning a single value from a function? .

我同意大多数用于证明多个返回值不是绝对必要的论点,我理解为什么没有实现这样的功能,但我仍然不明白为什么我们不能使用多个调用者-保存寄存器,如 ECX 和 EDX 以返回此类值。

使用寄存器而不是创建类/结构来存储这些值或通过引用/指针传递参数会不会更快,这两者都使用内存来存储它们?如果可以这样做,是否有任何 C/C++ 编译器使用此功能来加速代码?

编辑:

理想的代码应该是这样的:

(int, int) getTwoValues(void) { return 1, 2; }

int main(int argc, char** argv)
{
    // a and b are actually returned in registers
    // so future operations with a and b are faster
    (int a, int b) = getTwoValues();
    // do something with a and b
    
    return 0;
}

最佳答案

是的,有时会这样做。如果您在 x86 calling conventions 上阅读维基百科页面在 cdecl 下:

There are some variations in the interpretation of cdecl, particularly in how to return values. As a result, x86 programs compiled for different operating system platforms and/or by different compilers can be incompatible, even if they both use the "cdecl" convention and do not call out to the underlying environment. Some compilers return simple data structures with a length of 2 registers or less in the register pair EAX:EDX, and larger structures and class objects requiring special treatment by the exception handler (e.g., a defined constructor, destructor, or assignment) are returned in memory. To pass "in memory", the caller allocates memory and passes a pointer to it as a hidden first parameter; the callee populates the memory and returns the pointer, popping the hidden pointer when returning.

(强调我的)

最终,它归结为调用约定。您的编译器可以优化您的代码以使用它想要的任何寄存器,但是当您的代码与其他代码(如操作系统)交互时,它需要遵循标准调用约定,通常使用 1 个寄存器返回值。

关于c++ - 关于在 C/C++/Assembly 中返回多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31497152/

相关文章:

assembly - 使用 cmpq 和 je 时的无限循环

windows - 在 x64 64 位 Windows 上使用 NASM(和 GoLink)的 Hello World

c++ - 我必须学习哪种 C++ 才能制作自己的操作系统内核?

performance - 加速 IO 绑定(bind) OpenGL 应用程序

optimization - 如何使用 prefetch 插件来分析工具来优化 webpack 构建时间?

c++ - 预编译 header 和 __AFXWIN_H__

c++ - "Error: expected a ' { ' introducing a lambda body"尝试从 map<char,char> C++ 获取 char

c++ - 应用考虑特定边缘子集的算法

c++ - 使用 directx 11 时出现 Unresolved 链接错误

function - R 中的内置函数通常是否经过优化?