在C ++中具有虚拟继承的类大小 [英] Class sizes with virtual inheritance in C++

查看:195
本文介绍了在C ++中具有虚拟继承的类大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>

using namespace std;

class abc
{
    int a;
};
class xyz : public virtual abc
{
    int b;
};

int main()
{
    abc obj;
    xyz obj1;
    cout<<endl<<sizeof(obj);
    cout<<endl<<sizeof(obj1);
    return 0;
}

答案将取决于编译器,但是当我看到结果

The answers would be compiler dependent but I'm surprized when I saw this as the result

~/Documents/workspace/tmp ‹.rvm-›  $ ./class_sizes   

4
16



如果我删除了虚拟关键字,那么分配的大小分别为4和8这是我的期望。

If I remove the virtual keyword then the size allocated is 4 and 8 respectively which is what I expected.

为什么要占用额外的空间?
我怀疑它是为了vptr表或某种排序,但不知道确定。

Why is the extra space being taken up exactly? I suspect it is for the vptr table or something of that sorts but don't know for certain.

推荐答案

有关GCC中虚拟和多重继承的好文章是这一个 (Internet Archive Permalink)

A good article on virtual and multiple inheritance in GCC is this one (Internet Archive Permalink):

http://phpcompiler.org/articles/virtualinheritance.html

然而它不能完全回答你的问题,因为你从你使用的任何(未指定)编译器和构建设置中获得20个字节的输出

Yet it doesn't quite answer your question, as you are getting an output of 20 bytes out of whatever (unspecified) compiler and build settings you are using.

如果您使用GCC (至少在IDEone使用的默认设置下),那么您将获得12个字节。这和你写的东西是一样的:

If you were using GCC (under the default settings IDEone uses, at least), then you would be getting 12 bytes. Which is the same thing as what it would give had you written:

class abc
{
    int a;
    virtual void foo() {}
};
class xyz : public abc
{
    int b;
};

当它包含虚方法时,您是否实际上继承了abc:

Were you to virtually inherit from abc when it contains virtual methods:

class abc
{
    int a;
    virtual void foo() {}
};
class xyz : virtual public abc
{
    int b;
};

...那么你将从GCC中获得16个字节。

...then you would get 16 bytes out of GCC.


为什么要占用额外的空间?我怀疑它是为vptr表或某些类型,但不知道一定。

Why is the extra space being taken up exactly? I suspect it is for the vptr table or something of that sorts but don't know for certain.

如果我不得不做一个关于你的16字节方差的猜测:我可以看看你的编译器的虚拟继承的实现是否像所有虚拟基类一样,就像他们有虚拟方法,即使他们没有?

If I had to make a wild guess about your 16 byte variance: I might look into if your compiler's implementation of virtual inheritance treats all virtual base classes as if they had virtual methods, even if they didn't?

但我差不多做了这个。如果你想测试这个理论,你必须进一步看看;它依赖于实现。

But I pretty much made that up. You'll have to look further under the hood if you want to test the theory; it's implementation-dependent.

这篇关于在C ++中具有虚拟继承的类大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆