std::basic_string 的 libc++ 的 16 字节对齐模式背后的原因是什么?

What is the reasoning behind libc++'s 16-byte alignment pattern for std::basic_string?

在查看 the libc++ implementation of std::basic_string 时,我在第 1374 行看到了这个(在撰写本文时):

enum {__alignment = 16};

该值用于后续对齐计算,字符串大小请求四舍五入为该数字的倍数。

我可以接受 一些 舍入是为了避免内存碎片或其他什么,但是...

我想知道在这里使用硬编码 16 作为数字是否有任何特定的理由,或者它是否只是用作 "nice 'round' number" .

对于 64 位机器,16 等于 alignof( std::max_align_t ),这在某种程度上是有道理的。但是 __alignment 的完全相同的值也用于 32 位架构,所以...?

当我第一次设计 <string> 时,libc++ 还没有注定要开源。我只为 Apple 的平台写作。 Apple 的 malloc 总是分配至少 16 字节,并且是 16 字节的倍数,无论你要求多少(至少在 2007 年是这样,我最近没有检查)。

所以如果最常用的分配器要给你16个字节,你还不如用你的容量。

有一次,几年前,我尝试 change the allocator API so that it could ask the allocator how much memory it actually handed out for any particular request。但那次尝试失败了。因此,下一个最好的事情是利用代码将要处理的最常见分配器的先验知识。