如何确定对象的对齐方式
How to determine the alignment an object would like
我有一个之前分配的内存块,我想就地解释为 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";
首先,您尝试使用 reinterpret_cast
是不正确的,因为它会因违反严格的别名规则而导致未定义的行为。相反,您应该使用 placement new。
要正确对齐您的结构,您可以将 std::align
与 std::alignof
一起使用。
alignof
运算符会告诉您类型所需的对齐方式。例如 const auto byteBoundary = alignof(Object);
.
考虑使用 std::aligned_storage
if you need to create aligned raw memory. You will also need to use placement new
以正确地成为您尝试使用 block
的 Object
的生命周期。
我有一个之前分配的内存块,我想就地解释为 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";
首先,您尝试使用 reinterpret_cast
是不正确的,因为它会因违反严格的别名规则而导致未定义的行为。相反,您应该使用 placement new。
要正确对齐您的结构,您可以将 std::align
与 std::alignof
一起使用。
alignof
运算符会告诉您类型所需的对齐方式。例如 const auto byteBoundary = alignof(Object);
.
考虑使用 std::aligned_storage
if you need to create aligned raw memory. You will also need to use placement new
以正确地成为您尝试使用 block
的 Object
的生命周期。