Union redux

deadalnix via Digitalmars-d digitalmars-d at puremagic.com
Tue Jun 2 14:01:59 PDT 2015


On Tuesday, 2 June 2015 at 05:07:43 UTC, Andrei Alexandrescu 
wrote:
> On 6/1/15 9:46 PM, deadalnix wrote:
>> No, I asked you what is the rationale used to get types with
>> postblit/destructor in unions (right now, the spec says no). I 
>> asked
>> about the rationale for introduction of element with 
>> destructor/copy
>> constructor in C++, but it turns out that the link provided 
>> also include
>> constructor, and, in fact, only explore the constructor case 
>> in the
>> rationale.
>
> From 
> http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2248.html:
>
> ========
> Unfortunately this brute-force approach cannot be extended to 
> every user-defined type that a programmer might want to pass 
> around transparently. As class types, unions are definitely 
> second class: although a union may define a constructor and 
> destructor for instances of its type, the standard does not 
> allow it to contain any member whose default constructor, copy 
> constructor, copy assignment operator, or destructor are 
> non-trivial. The reason for these tight restrictions is obvious 
> -- the compiler can hardly be expected to generate sensible 
> default special member functions for an object whose type will 
> only become known at run time, and therefore a 
> "lowest-common-denominator" policy applies. With the rules in 
> place, default initialization is effectively a no-op, likewise 
> destruction, and copying is performed using a low-level memcpy.
>
> This rules out the inclusion of "interesting" types, or else 
> requires the programmer to ignore good design practice in order 
> to make them conform to the straightjacket of trivial types 
> (see discussion in N2172).
>
> And yet the need for a "variant" data structure that can hold 
> one object of a set of unrelated types is a problem that arises 
> over and over [...]
> ========
>
> There are others to be found in related docs. The simple 
> explanation is that non-discriminated unions are most useful as 
> unstructured bags that allow their users to plant their own 
> types in whilst keeping their discriminant elsewhere. Planting 
> either gratuitous restrictions on the storable data, or smarts 
> regarding construction and destruction, simply reduces the 
> range of things that unions are good at.
>
> I don't know how to explain this better.
>

It is unfortunate that the explanation do not go over the 
constructor but no desturctor case (way more common in D than in 
C++). I think the case is not as strong for D, as a we already 
allow struct with constructor, contrary to C++ when this document 
was done. Still probably the right way forward, granted this is 
@system. When you are in union land, you are pretty much on your 
own anyway.


More information about the Digitalmars-d mailing list