虚拟类继承对象的大小问题 [英] Virtual class inheritance object size issue

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

问题描述

在此代码中,ob1的大小为16,这很好(由于虚拟指针),但我不明白为什么ob2的大小为24.

Here, in this code, the size of ob1 is 16 which is fine(because of the virtual pointer) but I can't understand why the size of ob2 is 24.

#include <iostream>
using namespace std;
class A {
    int x;
};
class B {
    int y, z;
};
class C : virtual public A {
    int a;
};
class D : virtual public B {
    int b;
};
int main() {
    C ob1;
    D ob2;
    cout << sizeof(ob1) << sizeof(ob2) << "\n";
}

我希望ob2的大小为20,但输出为24

I expect the size of ob2 as 20, but the output is 24

推荐答案

D类型的对象的一种可能的布局是:

One possible layout for objects of type D is:

+----------+
| y        |   The B subobject (8 bytes)
| z        |
+----------+
| vptr     |   vtable pointer (8 bytes)
|          |
+----------+
| b        |   4 bytes
+----------+
| unused   |   4 bytes (padding for alignment purposes)
+----------+

那将使sizeof(ob2) 24.

对齐要求是由实现定义的.大多数情况下,最大成员对象或子对象的大小决定了对象的对齐要求.在您的情况下,最大对象vtable指针的大小为8个字节.因此,该实现将对象对准8位边界,并在必要时添加填充.

Alignment requirements are defined by an implementation. Most of the time, the size of the largest member object or subobject dictates the alignment requirement of an object. In your case, the size of the largest object, the vtable pointer, is 8 bytes. Hence, the implementation aligns objects at 8 bit boundaries, adding padding when necessary.

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

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