This article mainly discusses the memory layout of C ++ pairs. How is a simple or complex C ++ class stored in memory?
Each class has data members and interfaces. Are they stored in the same way? Why does a virtual function incur storage overhead? What is the difference between static and non-static members of a class? This article will reveal the answers to these questions.
An empty class:
Class test {
}
C ++ supports an empty class. This empty class has no definitions and does nothing. Is sizeof (TEST) 0?
The answer is no. The size of sizeof (test) is generally one. The compiler inserts a placeholder byte. Why?
The following statement is provided:
Test A [10]; an array of test. If the size of test is 0, it is obvious that each element of a cannot be obtained.
A [0] And a [1] have the same address, which leads to a conflict.
Since empty classes do nothing, what is the use of empty classes? The answer is yes. C ++'s non-virtual member functions are stored separately, so only the function class is actually an empty class. In practical applications, these classes are too common. Another purpose is to use it as a label class in a template. There are many empty classes in the STL template traits.
A simple class:
Class {
Int X _;
Int Y _;
Int Z _;
Public:
A (int x, int y, int Z): X _ (x), Y _ (Y), Z _ (z ){}
Int getx () const {return X _}
}
The memory layout of this class is as follows:
Class memory layout only contains data members.
Function members do not exist together. Function members are stored separately. Why can it be stored separately? In general, the first member function is actually a hidden this pointer, which connects the function member and the data member. This enables separate storage.
So for instance A of A, sizeof (a) is actually equal to the size of three Int. In special cases where memory alignment is not considered, it is 3 * sizeof (INT)