Introduction
Various C + + implementations may have different memory layouts for C + + classes/objects, including the order of data members, the structure of virtual function tables (virtual TABLE:VTBL), the processing of inheritance relationships, and so on. Understanding the layout of C + + classes/objects is a great help in understanding the various mechanisms of C + + and designing and developing correctly and rationally.
Support for mainstream compilers
The 3 mainstream compilers described in this article provide the ability to print/export the memory layout of C + + classes/objects, and now use tables to list their characteristics and usage, and the code files for testing are listed in the post (data.cpp)
Compilers and validated versions |
Usage |
Description |
GCC 4.8.4 |
gcc-- Fdump-class-hierarchy data.cpp |
The exported layout diagram is in a. class file in the same directory as the Data.cpp, such as Data.cpp.002t.class, sample content: VTT for A a::_ztt1a:4u entries 0 ( (& a::_ztv1a) + 24u) 8 ((& a::_ztc1a0_1y) + 24u) ((& a::_ztc1a8_1z) + 24u) ((& A::_ZTV1A ) + 48u) Class A size=16 align=8 Base size=16 base align=8 A (0x0x7f9dbc60c540) 0 Vptridx=0u V Ptr= ((& a::_ztv1a) + 24u) Y (0x0x7f9dbc5c11a0) 0 nearly-empty Primary-for A (0x0x7f9dbc60c540) Subvttid x=8u X (0x0x7f9dbc5ccae0) 0 empty virtual vbaseoffset=-24 Z (0x0x7f9dbc5c1208) 8 Nearly-empty Subvttid x=16u vptridx=24u vptr= ((& a::_ztv1a) + 48u) X (0x0x7f9dbc5ccae0) alternative-path |
clang 3.4 |
Clang- Xclang-fdump-record-layouts data.cpp |
Data.cpp is required to do a sizeof evaluation of the related classes , output in stdout, similar to * * * Dumping AST Record Layout 0 | class A 0 | class Y (PRI Mary Base) 0 | (Y vtable pointer) 8 | class Z (base) 8 | (Z vtable pointer) 0 | Class X (virtual Base) (empty) | [Sizeof=16, Dsize=16, align=8 | nvsize=16, nvalign=8] |
VC + + 2010 |
Adding compilation options /d1reportsingleclasslayout< class name > : Output a single class-related layout Or /d1reportallclasslayout: Output all class-related layouts |
Compile-time output in the Output window, similar to the following: 1> class Asize (8): 1> +--- 1> | +---(base class Y) 1> 0| | {VBPTR} 1> | +--- 1> | +---(base class Z) 1> 4| | {VBPTR} 1> | +--- 1> +--- 1> +---(virtual base X) 1> +--- 1> 1> A::[email protected]@: 1> 0| 0 1> 1| 8 (Ad (y+0) X) 1> 1> A::[email protected]@: 1> 0| 0 1> 1| 4 (Ad (z+0) X) |
The code file used for the test
Data.cpp
#include <cstdio>classX {}; classY: Public VirtualX {}; classZ: Public VirtualX {}; classA: PublicY PublicZ {}; intMainintargcChar**argv) {printf ("Ptr:%lu\n",sizeof(void*)); printf ("X:%lu\n",sizeof(X)); printf ("Y:%lu\n",sizeof(Y)); printf ("Z:%lu\n",sizeof(Z)); printf ("A:%lu\n",sizeof(A));
return 0; }
The C + + object model uses GCC, clang, and VC + + to display memory layouts for C + + classes