本文介绍了为什么sizeof(Derived4)是8字节?我认为应该是5个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是给定程序的输出:

sizeof(Empty) 1
sizeof(Derived1) 1
sizeof(Derived2) 4
sizeof(Derived3) 1
sizeof(Derived4) 8
sizeof(Dummy) 1

这是程序:

#include <iostream>
using namespace std;

class Empty
{};

class Derived1 : public Empty
{};

class Derived2 : virtual public Empty
{};

class Derived3 : public Empty
{
    char c;
};

class Derived4 : virtual public Empty
{
    char c;
};

class Dummy
{
    char c;
};

int main()
{
    cout << "sizeof(Empty) " << sizeof(Empty) << endl;
    cout << "sizeof(Derived1) " << sizeof(Derived1) << endl;
    cout << "sizeof(Derived2) " << sizeof(Derived2) << endl;
    cout << "sizeof(Derived3) " << sizeof(Derived3) << endl;
    cout << "sizeof(Derived4) " << sizeof(Derived4) << endl;
    cout << "sizeof(Dummy) " << sizeof(Dummy) << endl;

    return 0;
}

Derived3的大小为1字节。那么为什么Derived 4的大小是8字节??如果对齐是答案,那么为什么在derived3的情况下没有对齐?

Size of Derived3 is 1 byte. Then why the size of Derived 4 is 8 bytes?? If alignment is the answer then why there is no alignment in case of derived3?

推荐答案

类。看起来如果一个类有一个虚拟基类,那么它的实现包含一个对这个虚拟基类的引用,在你的情况下等于4个字节。当添加char类型的数据成员时,它将用三个字节填充,以提供对基本虚拟类的引用的对齐。

It depends on alignments of data members within a class. It seems that if a class has a virtual base class then its realization contains a reference to this virtual base class that in your case is equal to 4 bytes. When you add data member of type char then it is padded with three bytes that to provide the alignment for the reference to the base virtual class.

这篇关于为什么sizeof(Derived4)是8字节?我认为应该是5个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 16:54