Null references redux
bearophile
bearophileHUGS at lycos.com
Wed Sep 30 15:20:25 PDT 2009
Michel Fortin:
> For a return value it's
> more troublesome because you're implicitly adding a promise that the
> function will not return null, and you might not realize it's wrong
> until it does indeed return null and your program crashes with a
> segfault.
I see.
It's a matter of how much you value safety in your language. If you want a safer language, like Cyclone tries to be, the compiler may disallow function signatures like:
extern(C) void* foo(size_t size);
And force to use:
extern(C) void*? foo(size_t size);
Because the D compiler can't be sure that foo() returns a nonnull. In such situation you may just use the function like that, that returns a nullable pointer. This gives no overhead, and no safety.
Or you can add a bit of overhead and use something like an enforce (or an if) to create a nonnullable pointer from the nullable result of foo().
Finally if you are very sure your C function never returns a null, and you really want to use a nonnullable pointer around in your code, but you don't want to pay for the little null test in the D code, then you hard cast the nullable pointer to a nonnullable one, but I hope this is done in really uncommon situations.
I think this may solve the problem in a good enough way.
Bye,
bearophile
More information about the Digitalmars-d
mailing list