Spec#, nullables and more

Simen kjaeraas simen.kjaras at gmail.com
Fri Nov 5 18:00:23 PDT 2010


Walter Bright <newshound2 at digitalmars.com> wrote:

> Adam D. Ruppe wrote:
>> A non-nullable type is basically just:
>>  struct NotNull(T) {
>>    T _payload;
>>    alias _payload this;
>>    invariant() {
>>        assert(_payload !is null);
>>    }
>> }
>>  If we could disable the default constructor, this approach might just  
>> work. Sure,
>> the checks here would be at runtime, but you'd have them without having  
>> to
>> manually write the assert each time.
>
> All that does is reinvent the null pointer seg fault. The hardware does  
> this for you for free.
>
> A null pointer is what's known as a "white hole", all attempts to access  
> the object are rejected.

I believe you managed to miss the important part, "If we could disable the
default constructor". The invariant here is not about using the NotNull!T,
but for when you assign to it. In other words:

struct NotNull( T ) if ( is( T == class ) || isPointer!T ) {
     private T _payload;
     alias _payload this;
     this( T data ) {
         assert( data !is null );
         _payload = data;
     }
     @disable this( );
     @disable void opAssign( T );
}

NotNull!T notNull( T )( T ptr ) {
     return NotNull!T( ptr );
}

It might not cover all bases, but the idea is it is impossible to create a
NotNull!T from a null T, and impossible to assign a null T to one.

-- 
Simen


More information about the Digitalmars-d mailing list