开发者

c++ class disassembly

开发者 https://www.devze.com 2023-03-14 09:49 出处:网络
I have the following code: class Base { public: int x,y; Base() { x=10; y=20; } virtual void myfunction() { }

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 th开发者_StackOverflow社区e instance, but now I'm pretty sure that var_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 into ecx before the constructor is called?


It's some internal variable for a compiler generated temporary.

When you write new Base, the compiler generates a call to the global operator new function, then calls the constructor on the returned address. Apparently, your compiler saves the address returned from operator new in memory, rather than keeping it in a register.


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++.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消