How does D handle null pointers?

Adam B cruxic at gmail.com
Fri Aug 20 19:43:00 PDT 2010


> C# and Java are badly designed, D may do better. In my opinion a better solution to this problem is to:
> 1) Introduce non-nullable pointers/references, to denote them I have proposed a trailing @.
> 2) Require explicit tests every time a nullable pointers/references is about to be dereferenced (and then after this test in the else branch the reference type "becomes" a non-nullable one. This is an application of the idea of "TypeState", used by the Mozilla Rust language. The type doesn't actually change, it's just its state that changes...).
>
> This way you don't need (most) implicit null checks.
>
> Bye,
> bearophile
>

I think I'm tracking with you, bearophile and it sounds like a good
solution. You are suggesting a compile-time null check, correct?
However, instead of non-nullable references I would argue that all
references be non-nullable by default (like Vala does).  For example:

-------------
char[]@ foo()
{
	if (some condition)
		return "yada";
	else
		return null;  //causes compile error if you remove the @ symbol above
}

int main(char[][] args)
{
	char[]@ s = foo();  //causes compile error if you remove @ symbol

	if (something)
	{
		assert(s != null);
		printf(s);  //causes compile error if you remove above assertion
	}
	else if (s == null)
		return 1;
		
	printf(s);  //causes compile error if you remove above assertion or
else-if condition
	return 0;
}
-------------

Vala has something kind of like this with their trailing '?' syntax
although the feature is not as thorough as the above.  (See
http://live.gnome.org/Vala/Tutorial#Methods)


More information about the Digitalmars-d mailing list