Union redux

deadalnix via Digitalmars-d digitalmars-d at puremagic.com
Mon Jun 1 12:00:52 PDT 2015


After discussion at DConf, it ends up that union have some lack 
of specification, and some nonsensical behavior right now. Here 
are some points discussed and possible solutions :

1/ .init for unions is not defined. I propose to define it as the 
.init of the first field + padding with 0s if the union is larger 
than its first member. It seems to be what is generated right now.

2/ Default constructor takes one argument per union's field and 
assign them all one over the other. This does not make any sense 
and need to be changed. Proposed solutions :
  a. Define one constructor for the first field.
  b. Define N constructors, one per field.
  c. Do not define constructors.

My preference goes for b, then a, then c, in that order.

3/ union and @safe is currently undefined. I proposed to make 
everything involving unions @system, and we will figure it out 
from there. At the very least, all union with indirections and 
fields having a posblit/destructor ust be @system.

4/ tupleof for unions generate a tuple will all field of the 
union. It does not make much sense, and it is unclear if tupleof 
can make sense at all on a union. Let's not have tupleof on union 
at all.

5/ union currently disallow members with postblit and/or 
destructor . It seems that this was needed in C++ as per Andrei's 
comments. It seems to me that, because of manual memory 
management, C++ would have a lot more struct with copy 
constructor and/or destructor than in D, so I'm not sure if this 
require change in spec. Andrei, can you give more details on the 
C++ situation here ?

6/ struct with anonymous union in them define one parameter per 
union field in the default constructor. This should probably lead 
to the same solution as 2/

7/ struct with anonymous union in them have one entry per union 
field in their tupleof. All the union field should be present as 
one entry in the tupleof, with a compiler generated union type.

8/ unions and structs are mangled the same way (or so it seems). 
Bug or feature ?

9/ union alignement is not specified. union align should be least 
common multiple of union's fields.

10/ union that capture a closure are undefined. I think that 
right now, they just add the context pointer at the same address 
as other fields, which is nonsensical. Proposal :
  a. Add the context at an address that do not overlap with other 
fields.
  b. Do not allow union to capture a context.

Union can have member method and they could use captured info to 
know how to process the union in an opaque (voldemort) way. I see 
no reason to forbid it, and adding an exception for union create 
extra special casing (from a user standpoint) which is 
undesirable. My preference goes to a.



More information about the Digitalmars-d mailing list