Skeen Skeen - 1 year ago 222
C++ Question

alignas specifier and new, c++11

My question is rather simple;

Does the alignas specifier work with new?
That is, if a struct is defined to be aligned, will it be aligned when allocated with new?

Answer Source

If your type's alignment is not over-aligned, then yes, the default new will work. "Over-aligned" means that the alignment you specify in alignas is greater than alignof(std::max_align_t). The default new will work with non-over-aligned types more or less by accident; the default memory allocator will always allocate memory with an alignment equal to alignof(std::max_align_t).

If your type's alignment is over-aligned however, your out of luck. Neither the default new, nor any global new operator you write, will be able to even know the alignment required of the type, let alone allocate memory appropriate to it. The only way to help this case is to overload the class's operator new, which will be able to query the class's alignment with alignof.

Of course, this won't be useful if that class is used as the member of another class. Not unless that other class also overloads operator new. So something as simple as new pair<over_aligned, int>() won't work.

A proposal for C++17 (which has been accepted) adds support for dynamic allocation of over-aligned types, by having overloads of operator new/delete that take the alignof of the type being allocated. This will also support alignments of less than the max aligned type, so your memory allocator need not always return memory aligned to alignof(std::max_align_t).

That being said, compilers are not required to support over-aligned types at all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download