我正在阅读这篇文章“虚拟方法表”
上述文章中的示例:
class B1 {
public:
void f0() {}
virtual void f1() {}
int int_in_b1;
};
class B2 {
public:
virtual void f2() {}
int int_in_b2;
};
class D : public B1, public B2 {
public:
void d() {}
void f2() {} // override B2::f2()
int int_in_d;
};
B2 *b2 = new B2();
D *d = new D();
在文章中,作者介绍了object的内存布局d
是这样的:
d:
D* d--> +0: pointer to virtual method table of D (for B1)
+4: value of int_in_b1
B2* b2--> +8: pointer to virtual method table of D (for B2)
+12: value of int_in_b2
+16: value of int_in_d
Total size: 20 Bytes.
virtual method table of D (for B1):
+0: B1::f1() // B1::f1() is not overridden
virtual method table of D (for B2):
+0: D::f2() // B2::f2() is overridden by D::f2()
问题是关于d->f2()
。调用d->f2()
将B2
指针作为this
指针传递,因此我们必须执行以下操作:
(*(*(d[+8]/*pointer to virtual method table of D (for B2)*/)[0]))(d+8) /* Call d->f2() */
为什么我们应该将B2
指针作为this
指针而不是原始D
指针传递???我们实际上是在调用 D::f2()。根据我的理解,我们应该传递一个D
指向this
D::f2() 函数的指针。
___更新____
如果传递一个B2
指向this
D::f2() 的指针,如果我们想访问B1
D::f2() 中的类成员怎么办?我相信B2
指针(this)显示如下:
d:
D* d--> +0: pointer to virtual method table of D (for B1)
+4: value of int_in_b1
B2* b2--> +8: pointer to virtual method table of D (for B2)
+12: value of int_in_b2
+16: value of int_in_d
它已经有了这个连续内存布局的起始地址的一定偏移量。例如,我们想访问b1
D::f2() 内部,我猜在运行时,它会做类似的事情:(*(this+4)
指向this
与 b2 相同的地址) 这将b2
指向B
????