抱歉问了一个愚蠢的问题,但如果我需要确保结构/类/union 的对齐,我应该在 typedef 声明中添加 attribute((aligned(align))) 吗?
class myAlignedStruct{} __attribute__ ((aligned(16)));
typedef myAlignedStruct myAlignedStruct2; // Will myAlignedStruct2 be aligned by 16 bytes or not?
最佳答案
should I add attribute((aligned(align))) to typedef declaration?
不...typedef 只是指定的实际类型的假名或别名,它们不作为具有不同对齐、包装等的单独类型存在。
#include <iostream>
struct Default_Alignment
{
char c;
};
struct Align16
{
char c;
} __attribute__ ((aligned(16)));
typedef Align16 Also_Align16;
int main()
{
std::cout << __alignof__(Default_Alignment) << '\n';
std::cout << __alignof__(Align16) << '\n';
std::cout << __alignof__(Also_Align16) << '\n';
}
输出:
1
16
16
关于c++ - GCC 中的结构对齐(是否应在 typedef 中指定对齐?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6786138/