空的虚拟表可以存在吗? [英] Can an empty virtual table exist?
本文介绍了空的虚拟表可以存在吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <iostream>
using namespace std;
class Z
{
public:
int a;
virtual void x () {}
};
class Y : public Z
{
public:
int a;
};
int main()
{
cout << "\nZ: " << sizeof (Z);
cout << "\nY: " << sizeof (Y);
}
因为Y继承了Z,所以也会有虚表.美好的.但是,它没有任何虚函数,那么Y的虚表的内容是什么?
会空吗?
Because Y inherits Z, so it will also have a virtual table. Fine. But, it doesn't have any virtual functions, so what will be the contents of the virtual table of Y?
Will it be empty?
推荐答案
这完全取决于编译器. 当我强制实例化 Y
和 Z
,g++ 4.4.5
为 Y
和 Z
生成两个不同的虚拟表,它们具有相同的大小.
This is entirely compiler-dependent. When I force instantiation of Y
and Z
, g++ 4.4.5
produces two distinct virtual tables for Y
and Z
that have the same size.
两个表都指向相同的x()
但指向不同的typeinfo
结构:
Both tables point to the same x()
but point to different typeinfo
structures:
;=== Z's virtual table ===
_ZTV1Z:
.quad 0
.quad _ZTI1Z ; Z's type info
.quad _ZN1Z5xEv ; x()
_ZTI1Z:
; Z's type info (omitted for brevity)
;=== Y's virtual table ===
_ZTV1Y:
.quad 0
.quad _ZTI1Y ; Y's type info
.quad _ZN1Z5xEv ; x()
_ZTI1Y:
; Y's type info (omitted for brevity)
这篇关于空的虚拟表可以存在吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文