简体   繁体   English

C ++构造函数存储在哪里?

[英]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. 构造函数填充对象的vtable。
  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. 使用汇编语言源的要求是由于您无法从原始C ++代码确定machine-langage命令的内存占用量。 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: 例如,在x86_64上,您可以执行以下操作以获取调用方中下一条指令的地址:

In get_next_instruction_address.h get_next_instruction_address.h

extern "C" unsigned long get_return_address();

In get_next_instruction_address.S 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. 现在,当您调用get_next_instruction_address() ,返回的值将是函数调用完成后下一条指令(在汇编中)的值。 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. 使用在构造函数的汇编代码中进行函数调用的位置,然后允许您回溯并查看构造函数的起始地址的值是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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