我有一个先前分配的内存块,我想就地解释为struct
。如何确定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";
答案 0 :(得分:3)
alignof
运算符将告诉您类型所需的对齐方式。例如const auto byteBoundary = alignof(Object);
。
如果需要创建对齐的原始内存,请考虑使用std::aligned_storage
。您还需要使用placement new
来正确设置尝试使用Object
的{{1}}的生命周期。
答案 1 :(得分:2)
关闭后,您尝试使用reinterpret_cast
是不正确的,因为严格违反别名规则会导致不确定的行为。相反,您应该使用新的展示位置。
要正确对齐结构,可以将std::align
与std::alignof
一起使用。