Sunday 7 January 2018

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

itemprop="text">

The
std::aligned_storage structure provides a
type typedef that at least according to href="http://en.cppreference.com/w/cpp/types/aligned_storage" rel="nofollow
noreferrer">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 href="https://stackoverflow.com/questions/46457449/is-it-always-the-case-that-sizeoft-alignoft-for-all-types-t">clear
    to me that such a type can even
    exist.



Based on href="http://coliru.stacked-crooked.com/a/d27a419d81c12f2d" rel="nofollow
noreferrer">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).


class="post-text" itemprop="text">
class="normal">Answer



Per href="https://timsong-cpp.github.io/cppwp/meta.trans.other#2" rel="nofollow
noreferrer">[meta.trans.other]/2,





It is implementation-defined whether any extended alignment is
supported.




It's
pretty annoying when they specify stuff like this after the big table without a pointer.
I've just added the sentence to cppreference.



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...