How to align a structure element in D?

I tried this

struct Foo(T)
{
    align(8) void[T.sizeof] data;
}

but

static assert(Foo!(int).data.alignof == 8);

crashing saying alignment is still 1instead 8.

Why is this and how to fix it, so that it works for any arbitrary alignment that has a force of 2 (not only 8)?

+5
source share
1 answer

The DMD source view looks like this: alignofdoes not consider attributes align.

Here it is processed:

... if (ident == Id::__xalignof)
{
    e = new IntegerExp(loc, alignsize(), Type::tsize_t);
}

This converts the expression .alignofinto an expression size_twith a value alignsize(), so consider alignsize()for a static array:

unsigned TypeSArray::alignsize()
{
    return next->alignsize();
}

It just gets element type alignment ( void) in your case.

voidprocessed TypeBasic::alignsize()which just goes intoTypeBasic::size(0)

switch (ty)
{
    ...
    case Tvoid:
        size = 1;
        break;
    ...
}

, alignof, , align , . , .

+5

All Articles