c++ - `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 long
)long double
。但是关于 cppreference 的那个例子滥用了它。
解决方案
每种类型都有一个大小,并且该大小必须至少是其对齐方式(并且将是其对齐方式的倍数,就像任何类型一样)。因此,sizeof(max_align_t)
将不小于alignof(max_align_t)
。没有具体说明这个大小将超出多少,最终没有任何意义。
hardware_destructive_interference_size
cppreference 页面关于和之间的关系不正确max_align_t
。该标准仅规定它至少应为alignof(max_align_t)
字节。也就是说,最小的破坏性干扰至少是任何标量类型的对齐。
推荐阅读
- python - 将文件复制到文件夹
- java - Mockito:“给定......将”返回空值而不是答案
- objective-c - AVAssetExportSession 在尝试合并多个视频/音频剪辑时导致音频视频不同步
- php - 如果某个 API 不允许在 1 个 GET 请求中获取多个位置,那么 foreach 和每个位置发出 1 个 GET 请求是唯一的选择吗?
- xml - 如何使用 ET.parse 函数遍历目录中的每个文件
- entity-framework-core - 在 oData 控制器中检索上下文
- c++ - C 整数在 C++ 代码中使用时失去其常量状态
- php - PHP如何将结果保持为十进制格式并删除不必要的零?
- php - HTML 选择的问题
- firebase-analytics - 如何在 Firebase 分析中获取 screen_view 事件的计数?