Alignment of unions

Don nospam at nospam.com
Wed Apr 15 00:01:38 PDT 2009


Stewart Gordon wrote:
> Don wrote:
>> Stewart Gordon wrote:
> <snip>
>>> That's only because you want to be able to attach alignments to 
>>> individual members of a union.  And I still don't know why.
>>
>> I'm not sure why you think unions are so different to structs. They 
>> are identical in most respects -- including requirements for alignment 
>> of members.
> 
> I still don't know what you mean.

You're acting as if there's a big difference between unions and structs, 
and there isn't. Read the spec, the only differences are at 
construction, and struct literals.

>>> If you want a union to have a certain alignment relative to a struct 
>>> in which it's contained, in what cases is it not sufficient to put 
>>> the align attribute on the union's instance in the struct?
>>
>> In cases where you don't know what the containing struct is. The union 
>> may just be a type returned from a template, for example.
> 
> If you don't know what the containing struct is, you probably also don't 
> know what member alignment that struct requires. 

Yes you do. The union doesn't control the alignment of the surrounding 
struct. It only controls the alignment of itself inside that struct.

  The person who creates
> the struct, OTOH, does know.  

They do NOT know. Not without probing every member in the union.

So why are you trying to do that person's
> job?

No, you know what alignment the member requires.

By the way, there doesn't even need to be a surrounding struct!
An instance of the union on the stack may itself need to be aligned.
And you can even create a bare union on the heap.



More information about the Digitalmars-d mailing list