geeksforgeeks 018-c++中空的class大小不为0

为了保证两个不同的对象有不同的地址

1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
using namespace std;

class Empty { };

class Derived: Empty { int a; };

int ()
{
cout << sizeof(Derived);
return 0;
}

Output (with GCC compiler. See this):

1
4

以上程序输出不会大于4,一个空的基类不需要用单独一个byte来表示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#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 ()
{
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;
}

Output (with GCC compiler. See this):

1
2
3
4
5
6
sizeof(Empty) 1
sizeof(Derived1) 1
sizeof(Derived2) 4
sizeof(Derived3) 1
sizeof(Derived4) 8:虚继承会创建虚表,指针的大小是4char的大小是1,但是为了保证字节对齐,需要填充3个字节,总共是8
sizeof(Dummy) 1