The C++ implicit this, and exactly how it is pushed on the stack

随声附和 提交于 2019-12-05 05:09:12

This depends on the calling convention of your compiler and the target architecture.

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.

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 had a series some years ago on calling conventions. Here are the x86 and x64 articles.

This will depend on your compiler and architecture, but in G++ 4.1.2 on Linux with no optimization settings it treats this as the first parameter, passed in a register:

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;
}

Disassembly of 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

I just had a read of the C++ Standard (ANSI ISO IEC 14882 2003), section 9.3.2 "The this pointer", and it does not seem to specify anything about where it should occur in the list of arguments, so it's up to the individual compiler.

Try compiling some code with gcc using the '-S' flag to generate assembly code and take a look at what it's doing.

This sort of detail is not specified by the C++ standard. However, read through the C++ ABI for gcc (and other C++ compilers that follow the C++ ABI).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!