首页 > 解决方案 > `sizeof(std::max_align_t)` 有实际意义吗?

问题描述

C++ 介绍std::max_align_t

std::max_align_t 是一种普通的标准布局类型,其对齐要求至少与每个标量类型的对齐要求一样严格(一样大)。(来自http://en.cppreference.com/w/cpp/types/max_align_t

但没有说它的大小。(我还检查了 c++ 草稿)。

但是对于 x86-64 或 arm64,gcc 和 clang 都使用 size=32 和 align=16 来实现它。(上帝螺栓示例

在这个cppreference 示例中,2 * sizeof(std::max_align_t)它被用作std::hardware_destructive_interference_size(事实上,gcc 和 clang 都没有实现它)的后备。

#ifdef __cpp_lib_hardware_interference_size
    using std::hardware_constructive_interference_size;
    using std::hardware_destructive_interference_size;
#else
    // 64 bytes on x86-64 │ L1_CACHE_BYTES │ L1_CACHE_SHIFT │ __cacheline_aligned │ ...
    constexpr std::size_t hardware_constructive_interference_size
        = 2 * sizeof(std::max_align_t);
    constexpr std::size_t hardware_destructive_interference_size
        = 2 * sizeof(std::max_align_t);
#endif

那么sizeof(std::max_align_t)从 c++ 标准或 gcc/clang 实现中是否具有实际意义?或者为什么 gcc 和 clang 以大于对齐的大小来实现它?

此外,Apple M1 Macs 上的 clang 在std::max_align_t针对 arm64 时实现 size=8 和 align=8,但在针对 x86_64 时实现 size=16 和 align=16。

编辑:

gcc/ginclude/stddef.h std::max_align_t中定义为

/* Type whose alignment is supported in every context and is at least
   as great as that of any standard type not using alignment
   specifiers.  */
typedef struct {
  long long __max_align_ll __attribute__((__aligned__(__alignof__(long long))));
  long double __max_align_ld __attribute__((__aligned__(__alignof__(long double))));
  /* _Float128 is defined as a basic type, so max_align_t must be
     sufficiently aligned for it.  This code must work in C++, so we
     use __float128 here; that is only available on some
     architectures, but only on i386 is extra alignment needed for
     __float128.  */
#ifdef __i386__
  __float128 __max_align_f128 __attribute__((__aligned__(__alignof(__float128))));
#endif
} max_align_t;

但没有解释为什么long long __max_align_ll需要该成员。

我想一个可能的原因是 gcc 想要确保对齐max_align_t至少与 和 一样严格(一样大long longlong double。但是关于 cppreference 的那个例子滥用了它。

标签: c++

解决方案


每种类型都有一个大小,并且该大小必须至少是其对齐方式(并且将是其对齐方式的倍数,就像任何类型一样)。因此,sizeof(max_align_t)将不小于alignof(max_align_t)。没有具体说明这个大小将超出多少,最终没有任何意义。

hardware_destructive_interference_sizecppreference 页面关于和之间的关系不正确max_align_t该标准仅规定它至少应为alignof(max_align_t)字节。也就是说,最小的破坏性干扰至少是任何标量类型的对齐。


推荐阅读