I tried this
struct Foo(T)
{
align(8) void[T.sizeof] data;
}
but
static assert(Foo!(int).data.alignof == 8);
fails, telling me the alignment is still 1
instead of 8
.
Why is this, and how do I fix it, so that it works for any arbitrary alignment that is a power of 2 (not just 8)?
Data structure alignment is the way data is arranged and accessed in computer memory. Data alignment and Data structure padding are two different issues but are related to each other and together known as Data Structure alignment.
Memory align (for struct) Before each individual member, there will be padding so that to make it start at an address that is divisible by its alignment requirement. E.g., on many systems, an int should start at an address divisible by 4 and a short by 2.
Structure padding is a concept in C that adds the one or more empty bytes between the memory addresses to align the data in memory.
Browsing the DMD source, it looks like alignof
doesn't take into account align
attributes.
Here is where it is handled:
... if (ident == Id::__xalignof)
{
e = new IntegerExp(loc, alignsize(), Type::tsize_t);
}
This converts a .alignof
expression into a size_t
expression with value alignsize()
, so let's look at alignsize()
for a static array:
unsigned TypeSArray::alignsize()
{
return next->alignsize();
}
It just gets the alignment of the element type (void
) in your case.
void
is handled by TypeBasic::alignsize()
, which just forwards to TypeBasic::size(0)
switch (ty)
{
...
case Tvoid:
size = 1;
break;
...
}
Looking at how other types handle alignof
, it doesn't look like align
attributes are taken into account at all, but I could be wrong. It may be worth testing the alignment manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With