Alignment of struct and Class Members

Source: Internet
Author: User

Natural alignment

To ensure the stability and efficiency of CPU operations, the storage addresses of the basic data types in the memory must be naturally aligned. The so-called natural alignment means that variables of the basic data type cannot be simply stored in any address in the memory, and their starting addresses must be divisible by their size.

For example, on a 32-bit platform, the addresses of int and pointer variables can be divisible by four.

 

Natural alignment of struct Variables

For objects of the composite type (generally struct and class), if its starting address can meetStrictest requirements (highest)The data member's natural alignment requirements, then it is natural alignment.

What is "the strictest natural alignment requirement? For distance, the spaces occupied by double, Int, and bool are 8, 4, and 1 in sequence, and their alignment rigor is reduced in turn.

Alignment of the member variables in the struct according to the alignment requirements of the basic type variables with the largest sizeof size. When necessary, the end of the object must be filled with bytes.

Summary:The length of a struct must be an integer multiple of its longest member variable.

Example

 struct {// sizeof 8, aligned in 4 bytes, 2-byte long A1; short A2;} B; struct stest // sizeof 16 at the end, which is aligned by 8 bytes and filled with 7-byte {Double B; char ;}; struct threeeshort {// sizeof 10, aligned by 2 bytes, with 1-byte short a; short B; short C; short D; char ch ;}; 

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.