c++类拆解
我有以下代码:
class Base {
public:
int x,y;
Base() { x=10; y=20; }
virtual void myfunction() { }
};
int main() {
Base *b = new Base();
return 0;
}
反汇编给了我类似的内容:
push 0Ch ; size of Base
call j_<some giberrish> ; IDA gives the comment "operator new(uint)"
add esp, 4 ; function epilogue
mov [ebp+var_E0], eax
几行后,您将调用构造函数。
mov ecx, [ebp+var_E0]
call j_Base__Base
mov [ebp+var_F4], eax
- 起初我以为 var_E0 会包含指向实例的指针,但现在我很确定 var_F4 会包含构造函数的返回值。
- 那么,
var_E0
到底包含什么?为什么在调用构造函数之前将其移至 ecx 中?
I have the following code:
class Base {
public:
int x,y;
Base() { x=10; y=20; }
virtual void myfunction() { }
};
int main() {
Base *b = new Base();
return 0;
}
The disassembly gives me something like:
push 0Ch ; size of Base
call j_<some giberrish> ; IDA gives the comment "operator new(uint)"
add esp, 4 ; function epilogue
mov [ebp+var_E0], eax
A few lines later you have the constructor being called.
mov ecx, [ebp+var_E0]
call j_Base__Base
mov [ebp+var_F4], eax
- At first I had thought that
var_E0
would contain the pointer to the instance, but now I'm pretty sure thatvar_F4
does as it contains the return value of the constructor. - In that case, what does
var_E0
contain at all? Why is it moved intoecx
before the constructor is called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它是编译器临时生成的一些内部变量。
当您编写
new Base
时,编译器会生成对全局的调用operator new
函数,然后在返回值上调用构造函数地址。显然,您的编译器保存了从返回的地址
operator new
在内存中,而不是将其保存在寄存器中。It's some internal variable for a compiler generated temporary.
When you write
new Base
, the compiler generates a call to the globaloperator new
function, then calls the constructor on the returnedaddress. Apparently, your compiler saves the address returned from
operator new
in memory, rather than keeping it in a register.Visual C++ 使用内部约定,其中构造函数返回指向对象实例的指针(根据 C++ 标准,构造函数没有返回值)。因此,在您的情况下,var_E0 和 var_F4 都保存实例指针。
请查看我的文章,了解有关 Visual C++ 如何实现 C++ 的更多详细信息。
Visual C++ uses an internal convention where constructors return the pointer to the object instance (by C++ standard, constructors don't have a return value). So in your case both var_E0 and var_F4 hold the instance pointer.
Check my article for more details on how Visual C++ implements C++.
这几乎肯定是您正在查看的调试版本,并且调试版本对其所做的事情非常保守。创建对象是一个两个阶段的过程:分配内存,然后构造对象。您的编译器将分配的内存指针放入临时变量中。如果您构建优化版本,则不会存储此临时变量,因为这会引入不必要的开销(写入/读取 RAM)。
This is almost certainly a debug build you're looking at and debug builds are very conservative with what they do. Creating an object is a two stage process: allocate memory and then construct the object. Your compiler is putting the allocated memory pointer into a temporary variable. If you build an optimised version, this temporary variable won't be stored since that introduces an unnecessary overhead (writing/reading RAM).