Memory alignment rules (c++)

Alignment rules:

1. The first member is at the address whose offset from the structure is 0.

2. Other member variables should be aligned to an address that is an integer multiple of a certain number (alignment number). Note: Alignment = the smaller value between the compiler's default alignment and the member size. The default alignment number in VS is 8, and the default in Linux is 4.

3. The total size of the structure is: an integer multiple of the maximum alignment number (the largest variable type and the default alignment parameter are the smallest).

4. If a structure is nested, the nested structure is aligned to an integer multiple of its maximum alignment number, and the overall size of the structure is the integer of all maximum alignment numbers (including the alignment number of the nested structure) times.

#include <iostream>

using namespace std;

class A1{
	int a;
	char b;
}

class A2{
	char b;
	int a;
}

class A3{
	char a;
	double b;
	int c;
}

// 结构体嵌套
struct A5{
	double d;
	char c;
	int i;
}

struct A6{
	int f;
	char c;
	struct A5 a5;
}

int main() {
	cout << sizeof(A1) << endl;  // 8
	cout << sizeof(A2) << endl;  // 8
	cout << sizeof(A3) << endl;  // 24

	cout << sizeof(A5) << endl;  // 16
  // 4 + 4(因为a5对齐数是16和8的较小值,为8) + 16
	cout << sizeof(A6) << endl;  // 4 + 4 + 16
}

Why memory alignment?

1. Platform reason (transplant reason): Not all hardware platforms can access any data at any address; some hardware platforms can only fetch certain types of data at certain addresses, otherwise a hardware exception will be thrown.

2. Performance reasons: data structures (especially stacks) should be aligned on natural boundaries as much as possible. The reason is that to access unaligned memory, the processor needs to make two memory accesses; while aligned memory accesses require only one access.

Guess you like

Origin blog.csdn.net/LearnToStick/article/details/131789322