Chapter 1 Simple Object Model
1.1. Size of empty object
Let's look at the following
Class EMPTY
{
}
Empty This class does not contain, where there is no data and methods, then how much should we calculate the space size it occupied? Most people think it should be "0", which seems to be unquestionable because it is nothing, does not occupy space! But this is wrong? Let's test it.
We establish such a file Test.cpp, including the following code:
0001 #include
0002 #include
0003 Using Namespace STD;
0004 / / ----------------------------------- -----------------
0005 Class EMPTY
0006 {
0007};
0008 / / ----------------------------------------------- -----------------
0009 INT Main (int Argc, char * argv [])
0010 {
0011 COUT << "SIZEOF (EMPTY)" << '/ t' << sizeof (empty) << endl;
0012 getCH ();
0013 return 0;
0014}
0015 / / ----------------------------------------------- -----------------
Execute it, the output of GCC is "SizeOf (EMPTY) 1", the result of C Builder is "SizeOf (EMPTY) 8", all are not "0". Why is this? the reason is simple. Empty objects do not represent no objects. E.g:
EMPTY A, B;
IF (a == b)
{
// do something
}
If the size of A and B is "0", how do A and B determine if it is the same? They do not contain anything, can it recognize that these two objects are the same object? Obviously it is not possible. So how can you distinguish between them? This requires what they contain some. Then in fact, the memory layout of the EMPTY object should be
Char placeholder
EMPTY Object Memory Layout
1.2. Simple data object
After reviewing the empty object, let's take a look at the size of the object containing the data, as described below:
Class SIMPLE
{
Char a;
INT I;
}
What is its size? The int type takes up 4 byte spaces, and the char type takes up one byte space. The two should be "5", slowly, don't rush to the conclusion, let's verify it again, this time the result is " 8". Why is this this? Where is the extra 3 byte space from? This should be talked from the CPU bus. Now the computer CPU is generally 32-bit, the most efficient data transfer method is more than 4 bytes. In order to match the requirements of the CPU, the compiler uses the principle of completion. Try the char type to make up 3 bytes, so the size of the Simple object becomes "8". Its memory layout became
Char a (1 byte)
Suppose the placement (3 byte)
INT i (4 Byte) Simple object memory layout