www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 16104] New: Unions should allow fields with destructors,

https://issues.dlang.org/show_bug.cgi?id=16104

          Issue ID: 16104
           Summary: Unions should allow fields with destructors,
                    postblits, and invariants
           Product: D
           Version: D2
          Hardware: x86_64
                OS: Linux
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: andrei erdani.com

Consider https://dpaste.dzfl.pl/4897efa2f3e0, also copied here:

struct A1
{
    this(int) immutable {}
    //~this();
}

struct A2
{
    this(int) immutable {}
}

struct B
{
    union
    {
        A1 a1;
        A2 a2;
    }
    bool itsA2;
    this(int x) immutable
    {
        if (x < 0)
        {
            a1 = immutable(A1)(x);
        }
        else
        {
            a2 = immutable(A2)(x);
            itsA2 = true;
        }
    }
}

Here B is able to offer an immutable constructor because the typechecker
converts the first field assignment a1 = expr into a constructor call (not an
assignment). Then all we need to do is provide immutable constructors for A1
and A2. Neat.

Unfortunately, it all comes unglued if either or both A1 and A2 also offers a
destructor. In that case they can't be members of a union any longer, and the
consequence of that is, oddly, that objects with unions cannot offer immutable
constructors. E.g. uncommenting the dtor in A1 causes the error:

struct std.experimental.rc.B destructors, postblits and invariants are not
allowed in overlapping fields a1 and a2

This is an interesting example of interacting language features.

The solution is to allow literally any D type in a union. ALL TYPES. The very
point of the union is "put the layout here but enforce no guarantees about the
content; surrounding code will take care of that". So types with destructors,
postblits, and invariants should be gleefully allowed in unions. There would be
of course no calls to any of those.

This is a blocker for RCStr.

--
May 30 2016