Currently in @safe code, declaring struct variable which contains any overlapped pointer(==reference) fields is entirely disallowed.
struct S {
union {
size_t x;
int* y; // pointer field
}
int[] arr;
}
// This is necessary to avoid related compiler bug
S _dummy = S();
void test() @safe {
S s;
// Error: variable s unions containing pointers are not allowed
// in @safe functions
}
However I think this is too limited behavior. Even if S.y is an overlapped pointer field,
1. Declaring a variable typed S
2. Both reading and writing unoverlapped field S.arr
3. Both reading and writing overlapped field S.x
4. Writing overlapped pointer field S.y
should be allowed.
Especially, by combining #3 and #4, you can reinterpret int* to size_t under the @safe code. But it is nothing wrong, as same as
declaring size_t variable with void initializer.
void test() @safe {
size_t num = void;
}
Even the value of 'num' is garbage, using it won't cause any memory corruption in @safe. So currently it is properly accepted by compiler.
---
And the semantics should also work during CTFE. For CTFE, one following restriction is necessary.
- Any field value reinterpretation by using two overlapped fields is disallowed.
If it's detected in CTFE, should raise compile-time error.
Therefore, following code should work as expected.
bool test() {
S s; // declaration is OK
s.y = [1,2,3].ptr; // writing overlapped pointer field is OK
assert(s.y[0..3] == [1,2,3]); // reading valid field is OK
s.x = 10;
assert(s.x == 10);
// There's no reinterpretation between S.x and S.y
return true;
}
static assert(test()); // run CTFE
Comment #1 by k.hara.pg — 2013-11-13T07:11:59Z
(In reply to comment #0)
> // This is necessary to avoid related compiler bug
> S _dummy = S();
The "related bug" is bug 11427.