NotNull pointers

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Aug 29 13:46:30 PDT 2011


On 8/29/11 3:22 PM, Walter Bright wrote:
> For the latest dmd,
> https://github.com/D-Programming-Language/dmd/commit/1193f7828b444056c943742daae0a5ccf262272e
> ,
> I've implemented the ability to disable default initialization. This
> makes it practical to implement a library based "NotNull" type without a
> special syntax for it. The rationale for this is (rather than making it
> builtin) one can now build any type that is a restricted subset of
> another type. I suspect that a non-null type is just scratching the
> surface of this ability.
>
> Here's a draft prototype of the NotNull type:
>
> import std.c.stdio;
>
> struct NotNull(P) if (is(typeof({P p = null;})))
> {
> P p;
>
> this() @disable;
>
> this(P q)
> {
> assert(q);
> p = q;
> }
>
> NotNull opAssign(P q)
> {
> assert(q);
> p = q;
> return this;
> }
>
> alias p this;
> }
[snip]

This is very compelling. Great work! FWIW the implementation could be 
refined to never expose the held reference as an lvalue:

struct NotNull(P) if (is(typeof({P p = null;})))
{
     private P p;

     this() @disable;

     this(P q)
     {
         assert(q);
         p = q;
     }

     NotNull opAssign(P q)
     {
         assert(q);
         p = q;
         return this;
     }

     @property P get()
     {
         return p;
     }

     alias get this; // force rvalue access
}


Andrei


More information about the Digitalmars-d mailing list