使用__declspec的内存填充问题

Memory padding issues using __declspec

本文关键字:填充 问题 内存 declspec 使用      更新时间:2023-10-16

基于MSDN的__declspec(align(x))应该在成员变量之后添加x位填充,例如:

#include <iostream>
using namespace std;
void main()
{
    struct test
    {
        __declspec(align(32))char x;
          __declspec(align(32))int i;
          __declspec(align(32)) char j;
    };   
    cout << sizeof(test) << endl;//will print 96 which is correct
}

现在考虑以下情况:

#include <iostream>
using namespace std;
void main()
{
    struct test
    {
          char x;
          int i;
          char j;
    };   
    cout << sizeof(test) << endl;//will print 12
    //1 byte for x + 3 bytes padding + 4 bytes for i + 1 byte for j +3 bytes padding =12 
}

但是如果我把代码改成:

#include <iostream>
using namespace std;
void main()
{
    struct test
    {
          char x;
          int i;
          __declspec(align(1)) char j;
    };   
    cout << sizeof(test) << endl;//will print 12 again!!!!
}

为什么它给我12而不是9!我告诉编译器我不希望j.

后面有任何填充。

__declspec(align(1)) char j不做任何事情- char不需要与__declspec进行特殊对齐。

假设您稍后声明了一个test: test arr[2];数组。这里,arr[0].iarr[1].i必须在4字节边界上对齐;要求sizeof(arr[0])是4的倍数。