Re: using typedef to create aligned types

Daniel Glastonbury <[email protected]> Thu, 02 Dec 2004 11:12:49 +1000
Newsgroups gmane.games.devel.windows
Organization The Creative Assembly
Message-ID <[email protected]>
Andras Balogh wrote:

>Let Fred be:
>
>class Fred {
>public:
>	int helloiamfred;
>};
>
>then sizeof(Fred) will be 4
>
>but if I align the same class to 16 bytes:
>
>class __declspec(align(16)) Fred {
>public:
>	int helloiamfred;
>};
>
>then sizeof(Fred) will be 16!!!
>  
>
No it won't.

As others on the list have already said, in both cases sizeof(Fred) will
be 4 bytes.  It's still in int!

In the case of the aligned Fred, the alignment constraint means the
compiler will allocate the object on a 16 byte boundary[1].  If you
create an array of Freds, then the compiler will allocate the first Fred
on the boundary and then add 12 bytes of padding, before the next Fred.

This is the same as:

struct s
{
    unsigned char c;
    int i;
}

The language rules say that s.i needs to be aligned on a 4 byte
boundary, so the compiler will add 3 bytes of padding between s.c and
s.i.  (This can be overriden by the #pragma (pack) directive.)


>The reason is that if you want an array of Freds, each have to be aligned,
>so it's not just the base address, that's changed, but the padding too!
>  
>
Exactly.  The padding has changed.  Not the size of Fred.

Hope this helps to clear things up.

cheers
DanG

[1]  Of course heap allocated objects won't adhere to the constraint,
unless you use the aligned version of malloc.


-- 
Dan Glastonbury, Senior Programmer, The Creative Assembly
PO Box 883 Fortitude Valley, QLD, Australia. 4006
T: +617 3252 1359 W: http://www.creative-assembly.com.au
`Pour encourjay lays ortras'



-------------------------------------------------------
SF email is sponsored by - The IT Product Guide
Read honest & candid reviews on hundreds of IT Products from real users.
Discover which products truly live up to the hype. Start reading now. 
http://productguide.itmanagersjournal.com/
_______________________________________________
Gamedevlists-windows mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/gamedevlists-windows
Archives:
http://sourceforge.net/mailarchive/forum.php?forum_id=555