gpt4 book ai didi

c++ - 内存对齐高于最大对齐 alignas malloc

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:44:23 27 4
gpt4 key购买 nike

如何使用 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);

关于c++ - 内存对齐高于最大对齐 alignas malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42141219/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com