C++隐含了这一点,以及它是如何在栈上推送的

7 c++ assembly stack pointers this

我需要知道,当调用C++中的类方法时,隐含的'this'指针是第一个参数,还是最后一个.即:是否先将其推入堆栈或最后.

换句话说,我问的是编译器是否采用被调用的类方法:

int foo::bar(foo *const this, int arg1, int arg2); 
//or:
int foo::bar(int arg1, int arg2, foo *const this);
Run Code Online (Sandbox Code Playgroud)

因此,通过扩展,更重要的是,这也将回答G ++是否会分别将该指针推到最后或第一位.我审问谷歌,但我找不到多少.

作为旁注,当调用C++函数时,它们是否与C函数做同样的事情?即:

push ebp
mov ebp, esp
Run Code Online (Sandbox Code Playgroud)

总而言之:被调用的类方法看起来像这样吗?

; 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
Run Code Online (Sandbox Code Playgroud)

谢谢,非常感谢.

编辑:澄清事情,我正在使用GCC/G ++ 4.3

Mic*_*ael 15

这取决于编译器的调用约定和目标体系结构.

默认情况下,Visual C++不会在堆栈上推送它.对于x86,编译器将默认为"thiscall"调用约定,并将其传递给ecx寄存器.如果为成员函数指定__stdcall,它将作为第一个参数在堆栈上推送.

对于VC++上的x64,前四个参数在寄存器中传递.这是第一个参数,并在rcx寄存器中传递.

几年前雷蒙德·陈(Raymond Chen)有一个关于召集会议的系列文 这是x86x64文章.


Joh*_*kin 9

这取决于您的编译器和体系结构,但在没有优化设置的Linux上的G ++ 4.1.2中,它被视为this第一个参数,在寄存器中传递:

class A
{
public:
    void Hello(int, int) {}
};

void Hello(A *a, int, int) {}

int main()
{
    A a;
    Hello(&a, 0, 0);
    a.Hello(0, 0);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

反汇编main():

movl    $0, 8(%esp)
movl    $0, 4(%esp)
leal    -5(%ebp), %eax
movl    %eax, (%esp)
call    _Z5HelloP1Aii

movl    $0, 8(%esp)
movl    $0, 4(%esp)
leal    -5(%ebp), %eax
movl    %eax, (%esp)
call    _ZN1A5HelloEii
Run Code Online (Sandbox Code Playgroud)