D - Unsafe and doomed

Adam D. Ruppe destructionator at gmail.com
Mon Jan 6 07:49:10 PST 2014


On Monday, 6 January 2014 at 09:59:55 UTC, Organic Farmer wrote:
> Just found out that when I replace
>
> struct NotNull(T) { T obj; }
>
> with (http://arsdnet.net/dcode/notnull.d)'s definition of 
> NotNull it all makes sense.

Yes, it is very important to use the full type so you get the 
checks. The reason this is better than the segfault is that here, 
the run-time error occurs closer to the point of assignment 
instead of at the point of use.

my_function(enforceNotNull(obj)); // throw right here if it is 
null

This especially matters if the function stores the object 
somewhere. Having an unexpected null in the middle of a container 
can be a hidden bug for some time. Fixing it means finding how 
null got in there in the first place, and the segfault stack 
trace is almost no help at all. The not null things though catch 
it early and then the type system (almost*) ensures it stays that 
way.

* it is still possible to use casts and stuff to get a null in 
there but surely nobody would actually do that!


More information about the Digitalmars-d mailing list