Is allocating a buffer via new char[sizeof(T)]
guaranteed to allocate memory which is properly aligned for the type T
, where all members of T
has their natural, implementation defined, alignment (that is, you have not used the alignas
keyword to modify their alignment).
I have seen this guarantee made in a few answers around here but I'm not entirely clear how the standard arrives at this guarantee. 5.3.4-10 of the standard gives the basic requirement: essentially new char[]
must be aligned to max_align_t
.
What I'm missing is the bit which says alignof(T)
will always be a valid alignment with a maximum value of max_align_t
. I mean, it seems obvious, but must the resulting alignment of a structure be at most max_align_t
? Even point 3.11-3 says extended alignments may be supported, so may the compiler decide on its own a class is an over-aligned type?
new T
and cast the result? Oh, and +1 for teaching me a new tag. I never heard about language-lawyer. – Precedencesizeof
must be relevant too: 5.3.3-2 says "When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array" – Imprison[basic.align]/3
--[note every over-aligned type is or contains a class type to which extended alignment applies (possibly through a non-static data member) end note]
. I can't find the normative reference for this, but it seems to imply that your T will never be over-aligned. – Hindover-aligned
means !! – Shortcut[expr.new]/10
--[ Note: Because allocation functions are assumed to return pointers to storage that is appropriately aligned for objects of any type with fundamental alignment, this constraint on array allocation overhead permits the common idiom of allocating character arrays into which objects of other types will later be placed. — end note ]
. [continued...] – Hindalignas
is the only way in which over-aligned types can be created. – Hind