C++ object size, do you really know?

We are all until the size of char is 1 and int is 4. What is the size of the object in C++?

Look at three questions:

  1. Functions in C++ do not occupy the size of objects
  2. What is the size of the empty class?
  3. If there are virtual functions in the class, what is the size of the class?

1. Functions in C++ do not occupy the size of objects

Look at a piece of code:

It can be seen that the size of the class is the size of the attribute a of the class is 4, and the function does not occupy the size of the object.

So what is the reason for this?

the reason:

The advantage of this definition is to save space.

Suppose that there are 10 functions in the class at this time, and the class defines 100 objects. If each object contains the size of a function, then it needs to occupy 1000 function space locations, which consumes a lot of resources.

In fact, the function of the class is placed in the code area. Which object needs to call the function is called from the code area. Because the function is not a unique attribute of the object, there is no conflict, so only 10 function space positions are enough.

In this comparison, putting the function in the code area saves a lot of resources, so the function does not occupy the size of the object.

As for the location of the object, if new is in the heap area, otherwise it is in the stack area.

Second, what is the size of the empty class?

Look at the code:

We will find that the size of the empty class has become 1, shouldn't it be 0 normally?

The reason for this setting is because every object instantiation needs space, here the system defaults to a placeholder, which is 1 byte in size

3. If there are virtual functions in the class, what is the size of the class?

see the picture:

Comparing the above two cases, the size of the empty class is 1, but the function does not take up space. Why does the function become virtual but become 4?

Because when there is a virtual function, the compiler will add a virtual function pointer vptr to this class (32-bit is 4, 64-bit is 8)

At this point there are pointers in the class, so the size of the object becomes 4.

The above is the size of the different situations in the class.

Guess you like

Origin blog.csdn.net/qq_46423166/article/details/112298182