首页 > 解决方案 > 调整对齐的 Typedef

问题描述

gcc的“类型属性”页面提供了一个非常有趣的示例,说明如何调整类型别名的对齐方式:

typedef int more_aligned_int __attribute__ ((aligned (8)));
//                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

在这个例子中,more_aligned_int有不同的对齐方式int,这在声明这些家伙的数组时变得很明显:

aligned_int ar[3]; 

输出

error: alignment of array elements is greater than element size
       aligned_int ar[3];
                       ^

标准的 C++ 替代方案是alignas,虽然我很惊讶地发现您实际上可以编写:

using aligned_int = int alignas(8);

编译上述给出:

warning: attribute ignored [-Wattributes]
         using aligned_int = int alignas(8);
note: an attribute that appertains to a type-specifier is ignored 

所以没有副作用,这就是前面提到的数组声明成功的原因。提问时间:

标签: c++gcctypes

解决方案


这些不是一回事。一个是 GCC 扩展,另一个是标准语言功能。

来自cppreference.com

alignas 说明符可以应用于变量或非位域类数据成员的声明,也可以应用于类/结构/联合或枚举的声明或定义。它不能应用于函数参数或 catch 子句的异常参数。

所以标准功能不适用于int.

扩展确实如此(但随后您会违反数组不存在的后果)。

列举两个不相关的特征之间的所有差异可能没有用。

有没有一种标准的方法来为内置类型创建这样的 typedef(对齐调整)?

您可以将内置类型包装在 a 中struct

struct alignas(8) aligned_int
{
    int val;
};

aligned_int ar[3];

但请注意,这是可以编译的(可能是因为 的大小aligned_int已相应更改)。


推荐阅读