Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the memory layout of C++ objects?

Shulou Source: shulou.com Published: 2022-06-03 00:47:49 10月05日 Update

This article mainly explains "what is the memory layout of C++ objects". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. let's go deep into the editor's train of thought. Let's study and learn how the memory layout of C++ objects is.

Simple non-polymorphic memory layout

Class X {int x; float xx;public: X () {} ~ X () {} void printInt () {} void printFloat () {}}; |-| printZ (); / / Not OK, as virtual table of class Y doesn't have address of printZ () method

In the above code, y_ptr points to a child of class Y within the complete Z object.

As a result, call any method, such as using yroomptra-> printY (). The resolution method for using y_ptr is as follows:

(* yroomptra-> _ vtbl [2]) (y_ptr)

Virtual inheritance memory layout

Class X {int x;}; class Y: public virtual X {int y;}; class Z: public virtual X {int z;}; class A: public Y, public Z {int a;}

The layout is as follows:

| | Y class-> |-| |-| |-> |-| sub-object | Zpurpurz | |. |-|-| | Z::_vptr_Z |-| |-| A sub-object-- > | offset of X |-| offset of X | / / offset (12) starts from Z X class-> | XRV starts from Z X class | |-> |-| shared |-| |. | | sub-object |-| |

The memory representation of a derived class with one or more virtual base classes is divided into two regions: an invariant region and a shared region.

The data in the invariant region maintains a fixed offset from the starting position of the object, independent of subsequent derivations.

The shared area contains virtual base classes and then fluctuates in derivation and derivation order.

Thank you for your reading. the above is the content of "how is the memory layout of C++ objects". After the study of this article, I believe you have a deeper understanding of the memory layout of C++ objects. the specific use also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Objects memory members layouts functions compilers data compilers pointers static regions methods order centering pointing space code functions information content Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Shulou Tech Info vpn OPPO Reno Huawei