Data member model of C ++ object model (2)

zhaozj2021-02-17  54

1.2. Virtual inheritance and data member

Example of the following example:

0001 #include 0002 // ------------------------------------------- -------------------------- 0003 Class X {}; 0004 Class Y: Virtual public x}; 0005 Class Z: Virtual public x { }; 0006 Class A: Public y, public z {}; 0007 // --------------------------------- ---------------------------------- 0008 int main () 0009 {0010 cout << sizeof (x) < > i; 0016 }

There are two models, model one:

SIZEOF (X) = 1;

SIZEOF (Y) = 8;

SIZEOF (Z) = 8;

SIZEOF (a) = 12;

The model is as follows:

byte

Class X

1

Char One Byte Because X IS Empty

byte

Virtual base class x

Char one byte

Class Y | Class Z

4

VPTR

1

Char One byte Because Y is Empty

3

Padding 3 bytes

byte

Virtual base class x

Char one byte

Class A

4

VPTR_Y

4

VPTR_Z

1

Char One Byte Because A Is Empty

3

Padding 3 bytes

Model 2:

SIZEOF (X) = 1;

SIZEOF (Y) = 4;

SIZEOF (z) = 4;

SizeOf (a) = 8;

The model is as follows:

byte

Class X

1

Char One Byte Because X IS Empty

byte

Virtual base class x

Char one byte

Class Y | Class Z

4

VPTR

byte

Virtual base class x

Char one byte

Class A

4

VPTR_Y

4

VPTR_Z

The difference between the model two and models is that although the model III is empty, the subclavab is due to virtual inheritance, and no longer uses a byte placeholder, used to identify the difference between the object, the VPTR pointer It is already possible to distinguish between objects. Therefore, the subcaters in the model II do not need one byte placeholder, and because the pointer is 4 bytes, it will no longer need to make up, so that each sub-class object is less than the subclass of the model one. Occupy occupies 4 bytes.

转载请注明原文地址:https://www.9cbs.com/read-29283.html

New Post(0)