简体   繁体   中英

Where is C++ constructor stored?

I need to study how a Constructor of class initializes its object.

The key information about constructor behavior that I have is:

  1. Constructor fills the vtable of object.
  2. Constructor don't have name, hence no function-pointer.

How can I write code that will:

  1. get me address of constructor?
  2. trace the initialization of object?

Thanks in advance.

获取构造函数地址的更好方法就是围绕new编写一个包装器模板函数(使用C ++ 11完美转发,只需要一个)并获取其地址。

  1. get me address of constructor?

This will unfortunately be platform-specific and will require the use of assembly language. The basic technique you could use would be to make a call to a function that returns the address of the next instruction from the caller. From there, you could, by looking at the assembly-language source-code of the constructor generated by the compiler, determine the actual address of the constructor code in memory. The idea would be to see what address your function is called at, and then subtract from that address the number of bytes used up by any previous commands that compose the constructor function. The requirement for using the assembly-language source is due to the fact that you can't determine the memory foot-print of the machine-langage commands from the original C++ code. As noted, this would be highly platform and compiler-specific, and therefore a "non-portable" solution.

For instance, on x86_64, you could do the following to get the address of the next instruction in the caller:

In get_next_instruction_address.h

extern "C" unsigned long get_return_address();

In get_next_instruction_address.S

.section .text

.global get_next_instruction_address

get_next_instruction_address:
    movq (%rsp), %rax
    ret

Now when you call get_next_instruction_address() , the value returned will be the value of the next instruction (in assembly) after the function call is completed. Using where the function call takes place in the assembly code of the constructor will then allow you to back-track and see what the value of address of the start of the constructor is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM