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

--- Comment #0 from 2012-08-21 09:43:45 PDT ---
Component: DMD
Severity: major
Code number: 
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;



A comment by Andrei Alexandrescu:

> 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:
------- You are receiving this mail because: -------

Reply via email to