www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 19903] New: postblit called for uninitialised elements of

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

          Issue ID: 19903
           Summary: postblit called for uninitialised elements of unions
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: major
          Priority: P1
         Component: dmd
          Assignee: nobody puremagic.com
          Reporter: turkeyman gmail.com

import std.stdio;

    struct T
    {
        this(this) { writeln("dun postblit\n"); }
        float f = 0;
    }

    struct S
    {
        union {
            int x = 0;
            T y = void; // <- void initialised
        }
        int which = 0;
    }

    S a;
    S b = a; // <- assignment calls postblit


This assignment calls the T postblit, which is a `void` initialised member of a
union.
This is just a hard crash waiting to happen!

This pattern should be supplanted with copy-ctors.
I suggest a reasonable resolution is:
  1. no such implicit non-trivial assignment is attempted inside a union
  2. if a union contains an element with a non-trivial copy, then a copy-ctor
must be defined otherwise user receives a compile error informing them such.
    2a. perhaps rather than emitting a compile error, it might be better to
emit an automatic  disable copy constructor for that object.

I think it's the case that any union with elaborate copy semantics can only be
correctly composed by the author of the union.

--
May 26 2019