NotNull pointers

bearophile bearophileHUGS at lycos.com
Mon Aug 29 17:49:53 PDT 2011


Walter:

> Fixed. Keep 'em coming!

You are quick :-)

What's the way to solve this problem?

import core.stdc.stdio;

struct NotNull(P) if (__traits(compiles, {P p = null;})) {
     private P p;

     @disable this();

     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
}

class Foo {
    int x;
    this(int x_) { this.x = x_; }
}

alias NotNull!(Foo) nFoo;

// if nFoo is a good enough nonnull type, then this
// function should _never_ cause an Access Violation
void bar(nFoo foo) {
    printf("%d\n", foo.x);
}

void main() {
    auto a = new nFoo[5];
    bar(a[0]);
}

Bye,
bearophile


More information about the Digitalmars-d mailing list