C++ 结构尺寸12,结构对象对齐到8,可能吗?
我想定义一个结构,以便C++ 结构尺寸12,结构对象对齐到8,可能吗?,c++,visual-c++,C++,Visual C++,我想定义一个结构,以便sizeof(myStruct)=12,和\u alignof(myStruct)=8 struct myStruct{ int32_t a; int32_t b; int32_t c; }; 这可能吗 目前,我必须手动执行以下操作: __declspec(align(8)) myStruct str1; // Assume str1 start at 0x00 __declspec(align(8)) myStruct str2; // str2
sizeof(myStruct)=12
,和\u alignof(myStruct)=8
struct myStruct{
int32_t a;
int32_t b;
int32_t c;
};
这可能吗
目前,我必须手动执行以下操作:
__declspec(align(8)) myStruct str1; // Assume str1 start at 0x00
__declspec(align(8)) myStruct str2; // str2 address is 0x10
__declspec(align(8)) myStruct str3; // str3 address is 0x20
double abc; // abc address is 0x2C
__declspec(align(8)) myStruct str4; // str4 address is 0x38
对象的大小必须是其对齐要求的倍数。8不是12的系数。因此,不能使用大小为12、对齐方式为8的类型
您可以使用
alignas
说明符请求比类的子对象更严格的对齐,并且类的大小将相应增加。您的示例类将被填充到16个字节。C++的一个基本要求是数组<代码> t[n] < /代码>是代码> n*sieOf(t)< />代码,并且每个数组元素都正确地排列为<代码> t>代码>。这立即意味着类型的对齐必须划分其大小。
不要假设int
正好是4字节长。没有什么需要它。