我不明白为什么'Derived1'需要与'Derived3'相同的内存量

Tej*_*ana 6 c++ oop

在下面的代码中,我不明白为什么'Derived1'需要与'Derived3'相同的内存量.Derived 4的大小也是16的任何特定意义.

#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)

这段代码的输出是:

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

Bat*_*eba 8

A class必须具有sizeof1或更大,否则指针算法会破坏,并且数组的元素class将占用相同的内存.

因此sizeof(Derived1)至少是1 sizeof(Empty).空基优化意味着派生类的大小实际上为零.

sizeof(Derived3)也可以是1,因为单个成员是a char.请注意,编译器再次在此处利用空基优化.

由于编译器实现了多态行为的要求,因此多态类(即包含virtual关键字的类)具有更大的大小.