The memory layout of C + + object layout and multi-state realization exploration

Source: Internet
Author: User

To facilitate the analysis and observation of the object's memory layout, I set the struct Member alignment option to 1 bytes when code was generated, and the default is 8 bytes. If you are compiling the code in your own project, please do the same setup. Because I wrote some functions. Print layout information in an object, and if the object option is not 1 bytes, running the code will cause a pointer exception error.

Memory layout for normal class objects

First we start with the memory layout of the normal class object. C000 is an empty class, defined as follows:

struct C000

{};

Run the following code to print its size and the contents of the object.

Print_size_detail (c000)

The results are:

The size of c000 is 1

The detail of c000 is CC

You can see that it has a size of 1 bytes, which is a placeholder. We can see that its value is 0XCC. In debug mode, this represents the memory initialized by the debugging code inserted by the compiler. It may be a random value in release mode, and I'm testing for 0x00.

Define two classes, c010 and c011 are as follows:

struct c010

{

 c010() : c_(0x01) {}

 void foo() { c_ = 0x02; }

 char c_;

};

struct c011

{

 c011() : c1_(0x02), c2_(0x03) {}

 char c1_;

 char c2_;

};

Run the following code to print their size and the contents of the object.

Print_size_detail (c010)

Print_size_detail (c012)

The results are:

The size of c010 is 1

The detail of c010 is 01

The size of c011 is 2

The detail of c011 is 02 03

We can see from the object's memory output that their value is the value we assign in the constructor, c010 is 0x01,c011 as 0x0203. Sizes are 1, 2, respectively.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.