Does new char actually guarantee aligned memory for a class type?

后端 未结 2 911
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 15:15

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

相关标签:
2条回答
  • 2020-12-15 15:25

    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 ?

    As noted by Mankarse, the best quote I could get is from [basic.align]/3:

    A type having an extended alignment requirement is an over-aligned type. [ 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 ]

    which seems to imply that extended alignment must be explicitly required (and then propagates) but cannot

    I would have prefer a clearer mention; the intent is obvious for a compiler-writer, and any other behavior would be insane, still...

    0 讨论(0)
  • 2020-12-15 15:35

    The expressions new char[N] and new unsigned char[N] are guaranteed to return memory sufficiently aligned for any object. See §5.3.4/10 "[...] For arrays of char and unsigned char, the difference between the result of the new-expression and the address returned by the allocation function shall be an integral multiple of the strictest fundamental alignment requirement (3.11) of any object type whose size is no greater than the size of the array being created. [ 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 ]".

    From a stylistic point of view, of course: if what you want is to allocate raw memory, it's clearer to say so: operator new(N). Conceptually, new char[N] creates N char; operator new(N) allocates N bytes.

    0 讨论(0)
提交回复
热议问题