mercredi 27 septembre 2017

How can std::aligned_storage expose correctly aligned storage for any object?

The std::aligned_storage structure provides a type typedef that at least according to cppreference:

Provides the member typedef type, which is a PODType suitable for use as uninitialized storage for any object whose size is at most Len and whose alignment requirement is a divisor of Align.

The default value of Align is the most stringent (the largest) alignment requirement for any object whose size is at most Len.

In particular, with the default value of Align, the suitably aligned for any object whose size is at most Len.

Note that there are no caveats or exceptions for over-aligned types (and in any case the platform I'm using, gcc, supports at least some over-aligned types).

How can such an implementation actually work? To satisfy the requirement of "any object" it would seem that it would either:

  1. On a platform where alignof(T) <= sizeof(T) for types T, need to always align to roughly Len bytes, since an object of size Len could have an alignment of up to Len. Of course, this would waste a lot of memory for large Len!
  2. On a platform where alignof(T) may be larger than than sizeof(T), I don't see how it could be implemented at all. However, it isn't clear to me that such a type can even exist.

Based on my testing, for default Align values, gcc simply always aligns to 16, regardless of len. This means the storage is not suitable for any object, but only objects of fundamental alignment (alignof(max_align_t) == 16 on this platform).

Aucun commentaire:

Enregistrer un commentaire