gpt4 book ai didi

c++ - 如何确定对象的对齐方式

转载 作者:行者123 更新时间:2023-11-30 01:03:18 25 4
gpt4 key购买 nike

我有一个以前分配的内存块,我想将其解释为 struct。我怎样才能确定 block 中对 struct 具有最友好对齐方式的内存地址?

基本上,只需要知道用于确定给定 struct 最适合在哪个字节边界内工作的机制。

// psuedo-code

struct Object{
int theseMembersCould;
double beAnything;
char itsJustData[69];
}

// a chunk of previously allocated memory that I want to use
std::vector<uint8> block;
block.resize(1024);

uint32 byteBoundary = ????; // <-- this is what I want to discover

// math to get the nearest addr on the boundary (assumes byteBoundary will be POW2)
uint32 alignmentOffset= (byteBoundary - (block.data() & byteBoundary-1u)) & byteBoundary-1u;

Object * obj = new (block.data() + alignmentOffset) Object;
obj->itsJustData = "used as if it were a normal object beyond this point";

最佳答案

alignof运算符会告诉您类型所需的对齐方式。例如 const auto byteBoundary = alignof(Object);

考虑使用 std::aligned_storage如果您需要创建对齐的原始内存。您还需要使用 placement new正确地成​​为您尝试使用 blockObject 的生命周期。

关于c++ - 如何确定对象的对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53961346/

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