Preface
First of all, I would like to thank bolow for his guidance. He taught me how to view the C ++ memory layout under Visual Studio and did not dare to enjoy it exclusively.
1. How to view the memory layout using Visual Studio command line
CL test. CPP/d1reportsingleclasslayoutbase
For example, if you create a source file test. cpp with a class base, the above command can view the memory layout of the class base. Of course, here I assume that you will use the Visual Studio compilation tool Cl. If not, refer to the blog [C ++ Basics] 042 _ compiling source code with Visual Studio command line.
See the figure below to understand the C ++ memory Layout
The memory layout shown in a piece mainly includes: simple classes, complex classes with virtual functions, simple classes with inheritance relationships, and complex classes with inheritance relationships with virtual functions, multiple inheritance classes and diamond inheritance classes.
Although there are Foo functions in the class base, there is no Function Location in our memory layout. Why? Refer to another blog titled [C ++ Basics] 044_c ++ member function nature
Here we have a virtual function, but it only occupies 4 bytes. No matter how many virtual functions you have, it still occupies 4 bytes. It is just a pointer to the virtual function table.
When there is an inheritance relationship, the Child Class header is the memory layout of the base class.
When there is an inheritance relationship of the virtual function, the first stored is the virtual function table pointer.
Multiple inheritance. However, note that there are two virtual function table pointers.
Diamond inheritance relationship is not difficult, that is, to fill in the dead.
Other blog recommendations
Memory layout of C ++ objects (on): http://blog.csdn.net/haoel/article/details/3081328
Memory layout of C ++ objects (lower): http://blog.csdn.net/haoel/article/details/3081385