Given an existing type T, it is possible to overalign it on the stack with the alignas() keyword:
alignas(1024) T variable;
For dynamic allocation, we have a cumbersome syntax :
T *variable = new (std::align_val_t(1024)) T;
However, there are two problems with this syntax:
- Microsoft's compiler emits error C2956 although the syntax is valid;
- There seems to be no corresponding operator for destruction and aligned delete.
A workaround seems would be the definition of a new type that encapsulates T:
alignas(1024)
struct AlignedType {
T _;
};
Alignedtype variable = new AlignedType; // Properly aligned in c++17
delete variable; // Suitable aligned deallocation function called in c++17
This workaround is messy, if T's constructor has parameters, we must add some syntaxic shenanigan to forward constructor arguments, and we need to access variable._ to get the real content.
Inheritance is a bit simpler, but if T is a fundamental type (like uint32_t), we can't use inheritance.
My question is as follow:
Does something like
using AlignedType = alignas(32) T;
is possible (the above does not compile) or is it just not possible to dynamically allocate an existing type using custom alignment without resorting to syntaxic complexities ?