Disallow null references in safe code?

Idan Arye GenericNPC at gmail.com
Wed Feb 5 00:33:26 PST 2014


On Wednesday, 5 February 2014 at 03:12:57 UTC, Adam D. Ruppe 
wrote:
> On Tuesday, 4 February 2014 at 22:57:06 UTC, Idan Arye wrote:
>> So what you are saying is that it should be implemented in the 
>> core language(`@nullable`), and than wrapped in the standard 
>> library(`Nullable!`) so we can have the benefit of using D's 
>> and Phobos' rich template-handling functionality?
>
> That was my first thought but deadalnix mentioned a union with 
> typeof(null) which would achieve the same thing.
>
> so I think @nullable is useless and we should just focus on the 
> library type Nullable!T.
>
> There's lastly the question of
>
> if(nullable_ref) {
>   // nullable_ref is implicitly converted to not null
> }
>
> and meh, as far as I'm concerned, this is already a solved 
> problem:
>
> if(auto not_null = nullable_ref) {
>    // use not_null
> }
>
>
> But if we wanted the same name's type to magically change, I'd 
> prefer to add some kind of operator overloading to hook that in 
> the library too. Just spitballing syntax but
>
> struct Nullable(T) {
>     static if(__traits(potentiallyNullable, T)) {
>        union {
>           T payload;
>           typeof(null) _;
>        }
>        alias payload if;
>     } else {
>        struct {
>          T payload;
>          bool isNull;
>        }
>        T helper(out bool isValid) {
>             isValid = isNull;
>             return payload;
>        }
>        alias helper if;
>     }
>     /* other appropriate overloads/methods */
> }
>
>
> The last line is the magic. Unlike the existing technique, 
> opCast(T:bool)() {}, it would allow changing types inside the 
> if.
>
> Note that something can be done right now using opCast, a 
> helper type, and alias this: 
> http://arsdnet.net/dcode/notnullsimplified.d see checkNull 
> (thanks to Andrej Mitrovic for showing this to me)
>
> So I'm generally meh on it, but if we do want to do magic 
> changing types, I definitely want it available in the library 
> for more than just nullability.

The question is - will the optimizer be able to handle this as 
good as it could handle a built-in `@nullable`? If so - I'm all 
for it, but if not - D is still a system language and performance 
still counts.

Anyways, the order in the union should be reversed:

     union {
         typeof(null) _;
         T payload;
     }

The first field of the union is the one who gets initialized. If 
`T` is the first union "field", depending on how 
non-null-by-default will be implemented either an object of type 
`T` will be implicitly constructed or compilation will break when 
a nullable is created without initializing a value. If 
`typeof(null)` is the first union "field" it'll be initialized to 
`null` - as everyone should expect.


More information about the Digitalmars-d mailing list