虚函数表指针的位置
分类: C++/STL 2009-02-18 14:21591人阅读评论(1)收藏举报
XX软件公司的笔试题:
C++标准中,虚表指针在类的内存结构位置没有规定,不同编译器的实现可能是不一样的。请实现一段代码,判断当前编译器把虚表指针放在类的内存结构的最前面还是最后面。
当时的解答是:
#include <iostream>
using namespace std;
typedef unsigned (*Fun)(void);
class Base
{
public:
Base(void){}
virtual unsigned foo(void)
{
cout<<"Construct Base"<<endl;
return 1;
}
public:
virtual ~Base(){}
};
class Derive : public Base
{
public:
Derive(void){}
virtual unsigned foo(void)
{
cout<<"Construct Derive"<<endl;
return 1;
}
};
bool VtlInPre() /*判断虚表指针是否在类结构的前面,是,返回真*/
{
Derive dr;
int** pVtl = (int**)&dr;
Fun pFun = NULL;
pFun = (Fun)pVtl[0][0];
unsigned ret = 0;
ret = pFun();
return (ret == 1) ? true : false;
}
//test
int main()
{
bool tmp = false;
tmp = VtlInPre();
if(tmp)
{
cout<<"the pointer of vitrual table is in HEAD of class"<<endl;
}else
{
cout<<"the pointer of vitrual table is in END of class"<<endl;
}
return 1;
}
一般VC和BCB是将vPtr放在类实例的前四个字节,GCC是放在末尾。在某些情况下需要考虑表指针的位置,比如序列化的时
虚函数表指针的位置 来自淘豆网m.daumloan.com转载请标明出处.