如何确定对象想要的对齐方式

时间:2018-12-28 16:17:25

标签: c++ memory memory-alignment

我有一个先前分配的内存块,我想就地解释为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";

2 个答案:

答案 0 :(得分:3)

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

如果需要创建对齐的原始内存,请考虑使用std::aligned_storage。您还需要使用placement new来正确设置尝试使用Object的{​​{1}}的生命周期。

答案 1 :(得分:2)

关闭后,您尝试使用reinterpret_cast是不正确的,因为严格违反别名规则会导致不确定的行为。相反,您应该使用新的展示位置。

要正确对齐结构,可以将std::alignstd::alignof一起使用。