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

zhaozj2021-02-17  54

Chapter II Data Member Model

1.1. Inheritance and Data Member

Example of the following example:

0001 class Concrete10002 {0003 public: 0004 int val; 0005 char bit1; 0006}; 0007 class Concrete2: public Concrete10008 {0009 public: 0010 char bit2; 0011}; 0012 class Concrete3: public Concrete20013 {0014 public: 0015 char bit3; 0016 }

The inheritance relationship is as follows:

Concrete1

Concrete2

Concrete3

Correct object memory layout

Concrete1 Object Concrete2 Object Concrete3 Object

4

Int Val

1

Char bit1

3

Padding 3 bytes

8

Concrete1

1

Char bit2

3

Padding 3 bytes

12

Concrete2

1

Char bit3

3

Padding 3 bytes

Verify

0001 #include 0002 // ------------------------------------------- -------------------------- 0003 Class contrete10004 {0005 public: 0006 int val; 0007 char bit1; 0008}; 0009 Class Concrete2: Public contRete10010 {0011 Public: 0012 CHAR bit2; 0013}; 0014 Class Concrete3: Public contRete20015 {0016 public: 0017 char bit3; 0018}; 0019 // ----------------- ------------------------------------------------ 0020 INT Main () 0021 {0022 COUT << Sizeof (contRete1) << endl; 0023 cout << Sizeof (contRete2) << endl; 0024 cout << sizeof (contRete3) << endl; 0025 INT i; 0026 cin >> i ; 0027}

The output is:

8

12

16

As can be seen from the above model structure, the subclasses inherit the data of the parent class, and inherit the "extra" byte introduced by the parent class due to the principle of complement. Why don't you remove the "extra" bytes introduced by the child class while inheriting the parent class. Why don't you convert a model into a form in order to save memory, reduce the waste of object memory space caused by inheritance relationships?

Concrete1 Object Concrete2 Object Concrete3 Object

4

Int Val

1

Char bit1

3

Padding 3 bytes

4

Int Val

1

Char bit1

1

Char bit2

2

Padding 2 bytes

4

Int Val

1

Char bit1

1

Char bit2

1

Char bit3

1

Padding 1 Bytes, the memory occupancy size of the three objects becomes 8 bytes, so it will save memory when creating multiple derived class objects.

This model does not use this model because the model will generate unpredictable errors when copying the object, for example:

0001 Concrete2 * PC2; 0002 Concrete1 * PC1; 0003 PC2 = New Concrete2; 0004 PC1 = New Concrete1; 0005 * PC2 = * PC1;

The above model model will generate unpredictable errors in the fifth line because the data member of the Concrete2 object is destroyed when copying the Concrete1 object.

Bit2 will be assigned an uncertain value, breaking the original data content, this behavior is not expected.

Concrete1 Object Concrete2 Object

4

Int Val

1

Char bit1

3

Padding 3 bytes

4

Int Val

1

Char bit1

1

Char bit2

2

Padding 2 bytes

Copy

Similarly, Concrete1 ---> Concrete2, Concrete2 -à Concrete3 also destroyed data members.

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

New Post(0)