【发布时间】:2016-02-22 01:25:07
【问题描述】:
考虑下面的代码
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() {int temp=int_in_b1;} // override B2::f2()
int int_in_d;
};
以及对象 d 的以下内存布局:
d:
+0: pointer to virtual method table of D (for B1)
+4: value of int_in_b1
+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 *d = new D();
d->f2();
当d->f2();被调用时,D::f2需要访问来自B1的数据,但是修改了这个指针
(*(*(d[+8]/*pointer to virtual method table of D (for B2)*/)[0]))(d+8) /* Call d->f2() */
传给D::f2,那么D::f2怎么能访问呢?
代码来自:https://en.wikipedia.org/wiki/Virtual_method_table#Multiple_inheritance_and_thunks
【问题讨论】:
-
我不确定您所说的“修改此指针”是什么意思。一切运行良好,因为 D 中同时包含 B1 和 B2。当 D::f2 生成时,它知道如何从 this 中访问 int_in_b1 的 ussign 偏移量。
-
@SergeyA codepad.org/4DIgwoMe 查看输出。
-
我之前发过一些很蠢的cmets,请见谅。
-
我不清楚你在这里实际问的是什么。您是否有一些行为不端的代码,或者您只是在询问事情是如何工作的?
-
@EJP 我只是在问事情是如何运作的。
标签: c++ multiple-inheritance vtable abi virtual-functions