On 9/26/14 8:58 PM, H. S. Teoh via Digitalmars-d wrote:
On Fri, Sep 26, 2014 at 07:32:49PM -0400, Steven Schveighoffer via
Digitalmars-d wrote:
On 9/26/14 6:32 PM, H. S. Teoh via Digitalmars-d wrote:
Does the compiler infer it as @safe, though?
Hm... good point, I'm not sure if unions are considered @safe. But I
think that would be a decent enhancement request if not.
[...]
union U {
int* ptr;
long i;
}
void main() @safe {
U u;
u.i = 12345;
*u.ptr = 54321; // this can't possibly be @safe
}
How would the compiler decide which union operations are @safe and which
are not?
Well, if all unions members are of the same base type, and they only
differ by const (and by that I mean, const combined with either mutable
or immutable), then it should be safe.
So generically, these are @safe:
union
{
T t1;
const T t2;
}
union
{
immutable T t1;
const T t2;
}
This is not:
union
{
T t1;
immutable T t2;
}
checking current rules...
looks like @safe code doesn't flag unions as unsafe anywhere. I was even
able to dereference pointers that were union'd with ints.
But really, I think the most useful @safe rules would be:
1. A union of any number of non-reference types with the same mutability
throughout is @safe, even if the type varies.
2. A union of two non-reference types, in which one union member has
some bytes defined as mutable, and another union member has those same
bytes defined as immutable, is un-@safe. Const union members will not
disqualify the union.
3. A union of any number of pointer types which point at the same type,
but vary only by const, are @safe, unless at least one member is mutable
and at least one member is immutable.
4. Everything else is un-@safe
This may break some code, but I think it would define good starting
rules to allow this in @safe code.
-Steve