Bug 20068 – Union initialization in constructors should be @safe
Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2019-07-21T15:44:23Z
Last change time
2021-04-07T23:58:49Z
Assigned to
No Owner
Creator
Paul Backus
Comments
Comment #0 by snarwin+bugzilla — 2019-07-21T15:44:23Z
Currently, initializing a union is @safe, even if that union contains a pointer:
---
union A
{
int i;
int* p;
}
@safe void example(int* p)
{
A a = { p: p }; // compiles
}
---
However, if a constructor is used to initialize the union, it is considered @system:
---
union B
{
int i;
int* p;
@safe this(int* p)
{
// Error: cannot access pointers in @safe code that overlap other fields
this.p = p;
}
}
---
Since the first example is @safe, the second example should be @safe as well.
Comment #1 by dlang-bot — 2021-04-07T23:58:49Z
dlang/dmd pull request #12400 "Fix 20068 - Treat initialization of unions in constructors as @safe" was merged into master:
- fafefbc93f212d471b2cacf0208772e9a8d18286 by MoonlightSentinel:
Fix 20068 - Treat initialization of unions in constructors as @safe
Don't eagerly check the safety of a `DotVarExp` when determining
whether it's modifiable and instead defer it after the `ConstructExp`
lowerings.
This also ensures proper error messages when initializing an immutable
member twice.
https://github.com/dlang/dmd/pull/12400