Search code examples
c++stringc++11libc++

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


While looking at the libc++ implementation of std::basic_string, I came across this in line 1374 (at the time of writing):

enum {__alignment = 16};

This value is used in subsequent alignment calculations, string size requests being rounded up to multiples of this number.

I can accept that some rounding is going on to avoid memory fragmentation or whatever, but...

I wonder if there is any specific rationale behind using a hardcoded 16 as the number here, or if it's just used as a "nice 'round' number".

For a 64-bit machine, 16 amounts to alignof( std::max_align_t ), and that makes some sort of sense. But the exact same value for __alignment is used for 32-bit architectures as well, so...?


Solution

  • When I first designed <string>, libc++ wasn't yet destined to be open-source. I was writing for Apple's platforms only. And Apple's malloc always allocates at least 16 bytes, and in multiples of 16 bytes, no matter how much you ask for (at least this was true in 2007, I haven't checked recently).

    So if the most commonly used allocator is going to hand you 16 bytes, you might as well use them in your capacity.

    At one time, a few years earlier, I tried to change the allocator API so that it could ask the allocator how much memory it actually handed out for any particular request. But that attempt failed. So the next best thing was taking advantage of a-priori knowledge of the most common allocator the code was going to deal with.