Disallow null references in safe code?

Adam D. Ruppe destructionator at gmail.com
Sat Feb 1 20:00:56 PST 2014


On Sunday, 2 February 2014 at 00:50:28 UTC, Timon Gehr wrote:
> if(auto w = wn.checkNull){
>     // ...
> }else w.foo();

(presumably you meant wn.foo, as w would be out of scope in the 
else branch)

This is more a question of the default than the library though, 
as all other things being equal, changing the language so if(w) { 
/* w changes type */ }, still lets w.foo compile.

I have a radical idea about Foo, not sure if people would like it 
though... I'd like like the naked type to mean "borrowed, not 
null".

Then, Nullable!Foo is semi-magical in implementation, but 
semantically is basically struct Nullable(T) { bool isNull; T 
object; }.

It would *not* be a specialization of Foo; it does not implicitly 
convert and is not usable out of the box. You'd be forced to 
convert by checking with the if(w) kind of thing.

The magic is that Nullable!Foo is implemented as a plain old 
pointer whenever possible instead of a pointer+bool pair.


Probably nothing special there, all stuff you've heard of before 
and it is ground that C# IMO has covered fairly well.



The other thing I want though is to make it borrowed by default. 
A borrowed non-immutable object cannot be stored except in the 
scope of the owner. To store it, you have to assert ownership 
somehow: is it owned by the GC? Reference counted? Scoped, RAII 
style? Or DIY C style? You have to mark it one way or another. 
(This also applies to slices btw)


I say non-immutable since immutability means it never changes, 
which means it is never freed, which means ownership is 
irrelevant. In practice, this means all immutable objects are 
either references to static data or managed by the GC (which 
provides the illusion of an infinite lifetime).



This would be a radical change by default... but then again, so 
would not-null by default, so hey do it together I say.


More information about the Digitalmars-d mailing list