问题描述
我需要知道,当调用 C++ 中的类方法时,隐式this"指针是第一个参数还是最后一个参数.即:是先入栈还是最后入栈.
I need to know whether, when a class method in C++ is called, the implicit 'this' pointer is the first argument, or the last. i.e: whether it is pushed onto the stack first or last.
换句话说,我在问一个被调用的类方法是否被编译器认为是:
In other words, I'm asking whether a class method, being called, is taken by the compiler to be:
int foo::bar(foo *const this, int arg1, int arg2);
//or:
int foo::bar(int arg1, int arg2, foo *const this);
因此,通过扩展,更重要的是,这也将回答 G++ 是否会分别最后或第一个推送 this 指针.我询问了谷歌,但我没有找到太多.
By extension therefore, and more importantly, that would also answer whether G++ would push the this pointer last or first, respectively. I interrogated google, but I didn't find much.
附带说明一下,当调用 C++ 函数时,它们的作用与 C 函数相同吗?即:
And as a side note, when C++ functions are called, do they do the same thing as C functions? i.e:
push ebp
mov ebp, esp
总而言之:被调用的类方法会像这样吗?
All in all: would a class method being called look like this?
; About to call foo::bar.
push dword 0xDEADBEEF
push dword 0x2BADBABE
push dword 0x2454ABCD ; This one is the this ptr for the example.
; this code example would match up if the this ptr is the first argument.
call _ZN3foo3barEpjj
谢谢,非常感谢.
澄清一下,我使用的是 GCC/G++ 4.3
to clarify things, I'm using GCC/G++ 4.3
推荐答案
这取决于编译器的调用约定和目标架构.
This depends on the calling convention of your compiler and the target architecture.
默认情况下,Visual C++ 不会将其压入堆栈.对于 x86,编译器将默认使用thiscall"调用约定,并将 this 在 ecx 寄存器中传递.如果为成员函数指定 __stdcall,它将作为第一个参数压入堆栈.
By default, Visual C++ will not push this on the stack. For x86, the compiler will default to "thiscall" calling convention and will pass this in the ecx register. If you specify __stdcall for you member function, it will be pushed on the stack as the first parameter.
对于 VC++ 上的 x64,前四个参数在寄存器中传递.这是第一个参数,传入rcx寄存器.
For x64 on VC++, the first four parameters are passed in registers. This is the first parameter and passed in the rcx register.
几年前,Raymond Chen 有一个关于调用约定的系列.以下是 x86 和 x64 篇文章.
Raymond Chen had a series some years ago on calling conventions. Here are the x86 and x64 articles.
这篇关于C++ 隐含了 this,以及它是如何被压入堆栈的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!