编译器如何实现 __declspec(align(x)) / __attribute__((aligned(x)))?

How do compilers implement __declspec(align(x)) / __attribute__((aligned(x)))?

想象一下这样的结构:

struct S {
    __declspec(align(32)) double A[4]; // MSVC / ICL on Windows
    double A[4] __attribute__((aligned(x))); // CLANG / GCC
};

可以在堆栈上或使用 malloc 等方式分配结构,无论哪种方式,结构实例本身都可能不对齐。那么我们可以指望成员 A 是 32 字节对齐的吗?如果是这样,编译器是如何做到的?

至少对于 MSVC 来说,__declspec(align()) 的文档说它只影响静态和自动对象分配,而不影响动态分配。如果您想控制动态分配对齐,您将需要使用提供该功能的函数,例如 _aligned_malloc。