Opt-in non-null class references?

SimonN eiderdaus at gmail.com
Sat Mar 3 20:52:25 UTC 2018


On Saturday, 3 March 2018 at 18:28:42 UTC, aliak wrote:
> struct NonNull(T) if (isPointer!T || is(T == class))
> {
>   T value;
>   alias value this;
>   this(Args...)(Args args) { this.value = new T(args); } // 
> always force creation
> }

The pitfall here is that all structs must be 
default-constructible, and then all of the fields have the static 
init value:

     class A { this(int) { } }
     void main()
     {
         NonNull!A a;
         assert (a.value is null);
     }

...compiles and passes.

Wrapping class references in structs is costly, we lose a lot of 
automatic conversions across subclasses, const/immutable, ... For 
the over 90 % of references where null is a bug (sign of 
forgotten assignment), it will be convenient to keep D's 
references. A library solution must be super-convenient to be 
worthwhile here. For weeks, I've put off re-discussing non-null 
refs directly in D because a language change is a last resort.

> I'm going to experiment with moving Optional's methods out
> If you know of other ways though I'm all ears :)

No ideas for now, but I'll certainly follow this development 
closely, and will be happy to test things!

-- Simon


More information about the Digitalmars-d mailing list