为什么sizeof(Derived4)是8字节?我认为它应该是5个字节

Dev*_*wal 3 c++ sizeof virtual-inheritance memory-layout empty-class

这是给定程序的输出:

sizeof(Empty) 1
sizeof(Derived1) 1
sizeof(Derived2) 4
sizeof(Derived3) 1
sizeof(Derived4) 8
sizeof(Dummy) 1
Run Code Online (Sandbox Code Playgroud)

这是该计划:

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

Vla*_*cow 5

它取决于类中数据成员的对齐.似乎如果一个类有一个虚拟基类,那么它的实现包含对这个虚拟基类的引用,在你的情况下它等于4个字节.当您添加char类型的数据成员时,它将填充三个字节,以提供对基本虚拟类的引用的对齐方式.