Null references redux

Jarrett Billingsley jarrett.billingsley at gmail.com
Sat Sep 26 15:17:27 PDT 2009


On Sat, Sep 26, 2009 at 5:59 PM, Jeremie Pelletier <jeremiep at gmail.com> wrote:
>
> How would you do this then?
>
> void foo(int a) {
>        Object foo;
>        if(a == 1) foo = new Object1;
>        else if(a == 2) foo = Object2;
>        else foo = Object3;
>        foo.doSomething();
> }
>
> The compiler would just die on the first line of the method where foo is
> null.

Either use Object? (a nullable reference), or factor out the object
creation - use a separate method or something.

> What about "int a;" should this throw an error too? Or "float f;".

Those are not reference types. But actually, the D spec says it's an
error to use an uninitialized variable, so a compliant D compiler
wouldn't be out of line by diagnosing such things as errors if they
are used before they're intialized. Such a compiler would break a lot
of existing D code, but that's what you get for not following the
spec..

> What about standard pointers? I can think of so many algorithms who rely on
> pointers possibly being null.

Again, you have both nonnull (void*) and nullable (void*?) types.

> Maybe this could be a case to add in SafeD but leave out in standard D. I
> wouldn't want a nonnull reference type, I use nullables just too often.

You probably use them far less than you'd think.



More information about the Digitalmars-d mailing list