有关 C++ 内存对齐的测试

来源:互联网 发布:nginx squid 缓存 编辑:程序博客网 时间:2024/06/05 00:26

  • 测试环境
  • 无成员函数的结构体内存对齐测试
  • 有成员函数的结构体内存对齐测试
  • 有自定义变量的结构体内存对齐测试


测试环境

MBP macOS 10.12.1
Processor 2.8GHz Intel Core i7
Memory 16GB 1600MHz DDR3


无成员函数的结构体内存对齐测试

代码:

struct ExampleA {    int i;    double j;    std::string s;    int k;};void TestA() {    ExampleA e;    cout << "e:" << &e << endl; // 起始地址,与结构体内第一个成员的地址相同    cout << "e.i:" << &e.i << endl; // 起始地址,占8字节    cout << "e.j:" << &e.j << endl; // 占8字节    cout << "e.s:" << &e.s << endl; // 空串占32字节    cout << "e.k:" << &e.k << endl; // 占8字节    cout << "e.size:" << sizeof(e) << endl; // 一共8+8+32+8=56字节}

结论:对于基本类型,结构体默认选择字节最长的基本类型作为内存对齐大小,如果我将 double 和 string 注释掉,那么默认就是4字节对齐


有成员函数的结构体内存对齐测试

代码:

struct ExampleB {    void testFunc() {        cout << __FUNCTION__ << endl;    }    int i;    double j;};void TestB() {    ExampleB e;    cout << "e:" << &e << endl; // 起始地址,与结构体内第一个成员的地址相同    cout << "e.i:" << &e.i << endl; // 起始地址,占8字节    cout << "e.j:" << &e.j << endl; // 占8字节    // cout << "e.testFunc:" << &e.testFunc << endl; // 这样无法提取地址    cout << "e.size:" << sizeof(e) << endl; // 一共8+8=16字节}

结论:成员函数没有与成员变量共享一个内存地址块


有自定义变量的结构体内存对齐测试

代码:

struct ExampleC {    ExampleA a;    int i;    ExampleB b;    double j;};void TestC() {    ExampleC e;    cout << "e:" << &e << endl; // 起始地址,与结构体内第一个成员的地址相同    cout << "e.a:" << &e.a << endl; // 起始地址,占56字节    cout << "e.a.i:" << &e.a.i << endl; // 同测试A    cout << "e.a.j:" << &e.a.j << endl; // 同测试A    cout << "e.a.s:" << &e.a.s << endl; // 同测试A    cout << "e.a.k:" << &e.a.k << endl; // 同测试A    cout << "e.i:" << &e.i << endl; // 接 a 对象之后的地址    cout << "e.j:" << &e.j << endl; // 占8字节    cout << "e.b:" << &e.b << endl; // 占16字节    cout << "e.b.i:" << &e.b.i << endl; // 占8字节    cout << "e.b.j:" << &e.b.j << endl; // 占8字节    cout << "e.size:" << sizeof(e) << endl; // 一共8+8+16=32字节}

结论:自定义成员变量与普通成员变量展开一样,是连续的内存地址


CSDN 辣鸡 MD 编辑器,无序列表格式全丢