本文介绍了如何确定带有虚函数的sizeof类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个家庭作业问题。对于以下代码,

  #include< iostream> 
using namespace std;

class A
{
public:
virtual void f(){}
};

class B
{
public:
virtual void f2(){}
};

class C:public A,public B
{
public:
virtual void f3(){}
};

class D:public C
{
public:
virtual void f4(){}
};

int main()
{
cout<<<< sizeof(D)<<
}

输出结果是:8

有没有人可以解释一下它是8字节?如果vtable实现是编译器依赖,我应该在面试中回答这种问题?虚拟基类怎么样?



编辑:我在32位平台上工作。

解决方案

这当然是依赖于实现的。这将是一个可怕的面试问题。一个好的C ++程序员可以信任 sizeof 是正确的,让编译器担心这些vtable的东西。



但是这里发生的是一个典型的基于vtable的实现需要在 C D 的对象中有两个vtable。每个基类需要自己的vtable。由 C D 添加的新虚拟方法可以通过从一个基类扩展vtable格式来处理, 使用的vtables不能组合使用

在伪C代码中,下面是一个D类型的派生对象如何查看我的实现(g ++ 4.4.5 Linux x86):

  void * D_vtable_part1 [] = {(void *)0,& D_typeinfo,& A :: f1,& C :: f3,& D :: f4} 
void * D_vtable_part2 [] = {(void *)-4,& D_typeinfo,& B :: f2};

struct D {
void ** vtable_A;
void ** vtable_B;
};

D d = {D_vtable_part1 + 1,D_vtable_part2 + 1};


this is kind of homework question. For the following code,

#include <iostream>
using namespace std;

class A
{
public:
    virtual void f(){}
};

class B
{
public:
    virtual void f2(){}
};

class C: public A, public B
{
public: 
    virtual void f3(){}
};

class D: public C
{
public:
    virtual void f4(){}
};

int main()
{
    cout<<sizeof(D)<<endl;
}

The output is: 8

Could anyone please explain how it is 8 bytes? If the vtable implementation is compiler dependent, what should I answer for this kind of question in interviews? What about virtual base classes?

EDIT: i am working on a 32-bit platform.

解决方案

This is of course implementation-dependent. And it would make a terrible interview question. A good C++ programmer can just trust sizeof to be right and let the compiler worry about those vtable things.

But what's going on here is that a typical vtable-based implementation needs two vtables in objects of class C or D. Each base class needs its own vtable. The new virtual methods added by C and D can be handled by extending the vtable format from one base class, but the vtables used by A and B can't be combined.

In pseudo-C-code, here's how a most derived object of type D looks on my implementation (g++ 4.4.5 Linux x86):

void* D_vtable_part1[] = { (void*) 0, &D_typeinfo, &A::f1, &C::f3, &D::f4 };
void* D_vtable_part2[] = { (void*) -4, &D_typeinfo, &B::f2 };

struct D {
  void** vtable_A;
  void** vtable_B;
};

D d = { D_vtable_part1 + 1, D_vtable_part2 + 1 };

这篇关于如何确定带有虚函数的sizeof类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 12:38