Read-only property without @property

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Fri Sep 26 18:26:02 PDT 2014


On Fri, Sep 26, 2014 at 09:18:28PM -0400, Steven Schveighoffer via Digitalmars-d wrote:
> 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- at 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- at safe
> 
> This may break some code, but I think it would define good starting
> rules to allow this in @safe code.
[...]

Not a bad start. Though I do note that *declaring* an unsafe union
(according to the above definitions) is currently allowed in @safe code
by the compiler, but attempts to access a union member that overlaps
with a pointer is rejected. IOW, the compiler doesn't refuse definitions
of potentially unsafe unions, as long as you don't actually try to do
something unsafe with them. That might make unions more useful (they can
be passed around in @safe code as long as certain operations are
avoided), but probably also trickier to implement correctly.


T

-- 
Music critic: "That's an imitation fugue!"


More information about the Digitalmars-d mailing list