Bug 10512 – Reinterpret-casting struct fields as another struct should be @safe
Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-06-30T11:08:00Z
Last change time
2016-06-07T07:14:01Z
Keywords
safe
Assigned to
nobody
Creator
tommitissari
Comments
Comment #0 by tommitissari — 2013-06-30T11:08:15Z
The order and alignment of struct fields are statically known. Therefore the compiler should be able to verify that the following code is memory safe and let it compile:
@safe:
struct A
{
int i;
short s;
byte b;
}
struct B
{
long l;
int i;
short s;
byte b;
}
void main()
{
A a;
B b;
*(cast(A*) &b.i) = a; // [1]
}
[1] Error: cast from int* to A* not allowed in safe code
Comment #1 by maxim — 2013-06-30T11:40:49Z
These structs may come from different implementations with different alignments. In general case structs may include other aggregate types where situation may be complicated. D has unions for such tricks (you are better with placing long l in last place). In my opinion this is wontfix.