Bug 8576 – unions call destructors of all their fields
Status
RESOLVED
Resolution
DUPLICATE
Severity
major
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2012-08-21T09:43:00Z
Last change time
2013-05-18T13:30:15Z
Assigned to
nobody
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2012-08-21T09:43:45Z
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/[email protected]#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;
}
}
}
Comment #1 by maxim — 2013-05-18T13:30:15Z
*** This issue has been marked as a duplicate of issue 4421 ***