The C++ implicit this, and exactly how it is pushed on the stack(C++ 隐含了 this,以及它是如何被压入堆栈的)
问题描述
我需要知道,当调用 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,以及它是如何被压入堆栈的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 隐含了 this,以及它是如何被压入堆栈的
基础教程推荐
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01