Null references redux

language_fan foo at bar.com.invalid
Sat Sep 26 15:16:55 PDT 2009


Sat, 26 Sep 2009 14:49:45 -0700, Walter Bright thusly wrote:

> The problem with non-nullable references is what do they default to?
> Some "nan" object? When you use a "nan" object, what should it do?
> Throw an exception?

Well typically if your type system supports algebraic types, you can 
define a higher order Optional type as follows:

  type Optional T = Some T | Nothing

Now a safe nullable reference type would look like

  Optional (T*)

The whole point is to make null pointer tests explicit. You can pass 
around the optional type freely, and only on the actual use site you need 
to pattern match it to see if it's a null pointer:

  void foo(SafeRef[int] a) {
    match(a) {
      case Nothing => // handle null pointer
      case Some(b) => return b + 2;
    }
  }

The default initialization of this type is Nothing.

Some data structures can be initialized in a way that null pointers don't 
exist. In these cases you can use a type that does not have the 'Nothing' 
form. This can lead to nice optimizations. There is no default value, 
cause default initialization can never occur.



More information about the Digitalmars-d mailing list