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: nob...@puremagic.com ReportedBy: bearophile_h...@eml.cc --- Comment #0 from bearophile_h...@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/cqimoyzvlanjbmuzb...@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: -------