[Issue 8576] New: unions call destructors of all their fields

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Aug 21 09:43:47 PDT 2012


http://d.puremagic.com/issues/show_bug.cgi?id=8576

           Summary: unions call destructors of all their fields
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: normal
          Priority: P2
         Component: DMD
        AssignedTo: nobody at puremagic.com
        ReportedBy: bearophile_hugs at eml.cc


--- Comment #0 from bearophile_hugs at eml.cc 2012-08-21 09:43:45 PDT ---
Title: 
Component: DMD
Severity: major
Code number: 
Keywords: 
Outcome: wrong_code
Is done: no


import std.stdio;
struct Foo1 {
    ~this() { writeln("Foo1.dtor"); }
}
struct Foo2 {
    ~this() { writeln("Foo2.dtor"); }
}
struct Foo3 {
    ~this() { writeln("Foo3.dtor"); }
}
union U {
    Foo1 f1;
    Foo2 f2;
    Foo3 f3;
}
void main() {
    U u;
}


Output:

Foo3.dtor
Foo2.dtor
Foo1.dtor



A comment by Andrei Alexandrescu:
http://forum.dlang.org/thread/cqimoyzvlanjbmuzbtiy@forum.dlang.org#post-k0eclr:242093:241:40digitalmars.com

> That's pretty surprising. "Major bug" doesn't begin to describe it.
> Unions should call no constructors and no destructors.

-------------------------

But maybe there are alternative solutions. Elsewhere I have suggested an
*optional* standard method for unions, to be called at run-time by the garbage
collector to increase its precision when it has to deal with union instances.

When such activeField() method is defined, it may be called at the end of the
scope where the union is defined:


struct Foo {}
struct Bar {}

struct Spam {
    bool isBar;

    union {
        Foo f;
        Bar b;

        size_t activeField() {
            return isBar ? 1 : 0;
        }
    }
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list