Memory layout of C ++ objects (1)

Source: Internet
Author: User

This article mainly discusses the memory layout of C ++ pairs. How is a simple or complex C ++ class stored in memory?

Each class has data members and interfaces. Are they stored in the same way? Why does a virtual function incur storage overhead? What is the difference between static and non-static members of a class? This article will reveal the answers to these questions.

 

An empty class:

Class test {

}

C ++ supports an empty class. This empty class has no definitions and does nothing. Is sizeof (TEST) 0?

The answer is no. The size of sizeof (test) is generally one. The compiler inserts a placeholder byte. Why?

The following statement is provided:

Test A [10]; an array of test. If the size of test is 0, it is obvious that each element of a cannot be obtained.

A [0] And a [1] have the same address, which leads to a conflict.

Since empty classes do nothing, what is the use of empty classes? The answer is yes. C ++'s non-virtual member functions are stored separately, so only the function class is actually an empty class. In practical applications, these classes are too common. Another purpose is to use it as a label class in a template. There are many empty classes in the STL template traits.

 

 

A simple class:

Class {

Int X _;

Int Y _;

Int Z _;

Public:

A (int x, int y, int Z): X _ (x), Y _ (Y), Z _ (z ){}

Int getx () const {return X _}

}

The memory layout of this class is as follows:

Class memory layout only contains data members.

Function members do not exist together. Function members are stored separately. Why can it be stored separately? In general, the first member function is actually a hidden this pointer, which connects the function member and the data member. This enables separate storage.

So for instance A of A, sizeof (a) is actually equal to the size of three Int. In special cases where memory alignment is not considered, it is 3 * sizeof (INT)

 

 

 

 

 

 

 

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.