类的数据结构
Data Structure of Class
本文关键字:数据结构 更新时间:2023-10-16
C++类的数据结构是什么?它是如何在组装级别工作的?
IF语句是代码行的compare+条件跳转。
数组和字符串是数据的链环。
编译器为所有成员分配偏移量,并将这些偏移量包括在成员的所有加载/存储操作中:
struct foo {
uint32_t bar;
uint32_t baz;
uint32_t get_baz() { return baz; }
};
uint32_t get_baz_from_foo(foo *f) { return f->baz; }
变为(ARM汇编程序代码用于简化):
foo__get_baz:
; calling convention: this pointer in r3
; load 32 bit value from r3 + 4 bytes into r0
ldr r0, [r3, #4];
; calling convention: return value in r0
; return from subroutine
b lr
get_baz_from_foo:
; calling convention: first parameter in r0
; load 32 bit value from r0 + 4 bytes into r0
ldr r0, [r0, #4]
; calling convention: return value in r0
; return from subroutine
b lr
由于struct
各自的class
布局在编译后没有改变,因此此处将4硬编码到指令流中。
创建实例的方法是分配内存,并将指针从分配函数传递给每个期望指向结构的指针的人:
new__foo:
; two 32 bit integers need 8 bytes
; calling convention: first parameter in r0
mov r0, #8
; call allocator, which will then return to the function invoking new
bra malloc
如果有构造函数
struct foo2 {
foo2() : bar(5), baz(7) { }
uint32_t bar;
uint32_t baz;
uint32_t get_baz() { return baz; }
};
我们最终得到了一种稍微复杂一点的创建对象的方法(您应该能够在没有注释的情况下弄清楚):
new__foo2:
strdb lr, ![sp]
mov r0, #8
bl malloc
mov r1, #5
str r1, [r0]
mov r1, #7
str r1, [r0, #4]
ldaia lr, ![sp]
b lr
get_baz
的实现与foo
类的实现相同。
现在,如果我构建这样一个对象并获得baz值:
bl new__foo2
; remember: the this pointer goes to r3
mov r3, r0
bl foo2__get_baz
我最终得到了包含值7
的r0
。
对于virtual
方法,会创建一个隐藏的数据成员,它是指向函数表的指针:
struct base {
virtual uint32_t get_baz() = 0;
};
struct derived : base {
derived() : baz(5) { }
virtual uint32_t get_baz();
uint32_t bar;
uint32_t baz;
};
成为
new__derived:
strdb lr, ![sp]
mov r0, #12
bl malloc
mov r1, #5
str r1, [r0, #8]
; get the address of the vtable
ldr r1, =vtable__derived
; vtable typically goes to the end of the class defining it
; as this is the base class, it goes before derived's data members
str r1, [r0]
ldria lr, ![sp]
b lr
vtable__derived:
; pointer to function
dw derived__get_baz
derived__get_baz:
ldr r0, [r3, #8]
b lr
调用此函数是间接完成的:
; construct normally
bl new__derived
; here, we forget that this is a "derived" object
; this pointer to r3
mov r3, r0
; get vtable ptr
ldr r0, [r3]
; get function ptr from vtable
ldr r0, [r0]
; call function
bl r0
这里,r0
现在是5
,因为这就是构造函数存储在那里的内容。
相关文章:
- 链表,反向函数,数据结构
- 如何使用set实现无序数据结构?
- 我们可以将数据永久保存为数据结构吗?
- C++中的可变长度数组/数据结构
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 通过 NIF 从C++返回自定义数据结构
- 编译器上的策略数据结构不起作用
- 尝试构建"lock-free"数据结构C++
- 设计将引用元素移动到开头的数据结构.C++
- 在学习数据结构之前对STL有一个了解是好的吗?
- 如何解析表示树状数据结构的字符串
- 我对数据结构、双向链表有一些问题
- googletest:测试太大的数据结构
- C++中deque数据结构的大O是什么?
- 我可以使用哪种数据结构来处理这种方式
- 将文本文件解析为树状数据结构
- C++ 中具有 O(1) 搜索时间复杂度的数据结构
- 哪些存储了不完整类型的 STL 数据结构可以用作类成员?
- C++,您能否设计一种数据结构,将指针保存在连续内存中并且不会使它们失效?
- 带参数的数据结构的全局声明