Bug 19150 – Union member assignment causes invalid destructor call in @safe code
Status
RESOLVED
Resolution
DUPLICATE
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2018-08-08T18:53:29Z
Last change time
2019-05-28T11:51:46Z
Assigned to
No Owner
Creator
Paul Backus
Comments
Comment #0 by snarwin+bugzilla — 2018-08-08T18:53:29Z
The following code compiles without errors and produces an erroneous call to HasDtor's destructor:
---
struct HasDtor
{
int n;
~this() @safe
{
import std.stdio: writeln;
writeln("Called destructor with n = ", n);
}
}
union U
{
float n;
HasDtor h;
}
@safe void main()
{
U u = { n : 1 };
u.h = HasDtor(2);
}
---
Output:
Called destructor with n = 1065353216
Because there is no way to know at compile time whether the union member being assigned to is valid, assignment to a member of a union that includes any members with destructors should be forbidden in @safe code.
In addition, since the language must rely on the programmer to manually destroy the appropriate union member in @system code, the automatic destructor call is at best redundant and at worst undefined behavior. Therefore, it should be omitted.
Comment #1 by simen.kjaras — 2019-05-28T11:51:46Z
*** This issue has been marked as a duplicate of issue 19122 ***