将如何使用 malloc(或 new,因为在大多数实现中 new 是用 malloc 实现的,不确定标准对对齐和 new 的规定是什么,除了数据必须与最高标量对齐)与具有对齐要求设置为高于系统上的最大对齐要求 ( alignof(std::max_align_t)
)?所以像
alignas(alignof(std::max_align_t) + alignof(int)) struct Something {
...
};
将评论变成答案。
让ALIGNMENT
表示所需的对齐方式。
然后你可以安全地分配你的结构如下:
char* buffer = new char[ALIGNMENT+sizeof(Something)];
uintptr_t address = reinterpret_cast<uintptr_t>(buffer);
uintptr_t aligned_address = address+ALIGNMENT-address%ALIGNMENT;
Something* something = reinterpret_cast<Something*>(aligned_address);