gpt4 book ai didi

c++ - 调整对齐的Typedef

转载 作者:行者123 更新时间:2023-12-02 09:56:28 26 4
gpt4 key购买 nike

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

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

因此没有副作用,这就是上述数组声明成功的原因。提问时间:
  • 那么alignas不等于aligned属性吗?
  • 还有更多不同的方式吗?
  • 是否有用于为内置类型创建此类typedef(对齐调整)的标准方法?
  • 最佳答案

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

    cppreference.com:

    The alignas specifier may be applied to the declaration of a variable or a non-bitfield class data member, or it can be applied to the declaration or definition of a class/struct/union or enumeration. It cannot be applied to a function parameter or to the exception parameter of a catch clause.



    因此,标准功能不适用于 int

    该扩展确实可以(但是您可能会因此而陷入后果,以致该数组不存在)。

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

    Is there a standard way, for creating such typedefs (alignment tweaks) for built-in types?



    您可以将内置类型包装在 struct中:
    struct alignas(8) aligned_int
    {
    int val;
    };

    aligned_int ar[3];

    但是请注意 this compiles(大概是因为 aligned_int的大小已相应更改)。

    关于c++ - 调整对齐的Typedef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59663770/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com