基本数据类型声明
本人电脑的各个基本数据类型的大小如下:
Code:
#include <iostream>
using namespace std;
int main() {
cout << "char: " << sizeof(char) << endl; // 1
cout << "bool: " << sizeof(bool) << endl; // 1
cout << "int: " << sizeof(int) << endl; // 4
cout << "long: " << sizeof(long) << endl; // 4
cout << "long long: " << sizeof(long long ) << endl; // 8
cout << "float: " << sizeof(float) << endl; // 4
cout << "double: " << sizeof(double) << endl; // 8
return 0;
}
Out:
char: 1
bool: 1
int: 4
long: 4
long long: 8
float: 4
double: 8
结构体
Code:
#include <iostream>
using namespace std;
struct A {
bool one;
};
struct B {
int one; // 4
bool two; // 1
};
struct C {
bool one; // 1
int two; // 4
double three; // 8
};
struct D {
char one[10]; // 12
double two; // 8
double three; // 8
};
int main()
{
cout << "A: " << sizeof(A) << endl;
cout << "B: " << sizeof(B) << endl;
cout << "C: " << sizeof(C) << endl;
cout << "D: " << sizeof(D) << endl;
}
Out:
A: 1
B: 8
C: 16
D: 32
头部添加编译器指令:
#pragma pack(4)
Out:
A: 1
B: 8
C: 16
D: 28
内存对齐: 为了方便CPU的读取,编译器会让结构体中的数据进行一个固定数整数倍的对齐,而这个固定数则一般会采用4个字节和8个字节。一般决定因数是CPU的字长,即32bit字长,那么CPU对于4个字节的读取会比1个字节的读取,要更加的快速和方便。而换成64bit字长的CPU,想来8个字节的读取会更加的快速和方便。
而在特定平台的编译器上,一般会有默认"对齐系数"(也叫对齐模数),即不与当前CPU字长所相对应的对齐系数。可以通过预编译命令#pragma pack(n) 来改变这一系数,而其中n就是你要指定的"对齐系数"。
由此可见,我所使用的编译器MinGW-W64 gcc version 8.1.0
所默认使用的对齐系数是8字节,也就是对应64bit的CPU。