null and type safety
Brendan Miller
catphive at catphive.net
Mon Nov 3 13:10:29 PST 2008
So I'm curious about D as a programming language, especially as it compares to C++.
One problem that C++ made a partial effort to solve was that normal pointers in C++, and references in languages like Java and C# essentially aren't type safe.
Consider that null can always be assigned to a pointer or reference to type T in those languages, and null is clearly *not* of type T, thus operations on a variable denoted of type T, are doomed to fail.
T *myObject = null;
myObject->myMethod(); // fails, despite the fact that myObject is of type T
// and myMethod is defined for type T.
Null is a holdover from C and has no place in a typesafe language. The designers of C++ knew this, and so introduced the c++ reference type:
T &myObjectRef = ...;
which cannot be null.
T &myObjectRef = null; // fails at compile type
T &myObjectRef = *ptr; // if ptr is null, operation is "undefined".
The designers of Java and C#... copied C's typesystem largely for marketing purposes and never really thought through these issues (although I read an interview where Anders Hejlsberg admitted this was a mistake with C# that occured to him too late to fix).
This is obviously a problem. Everyone knows that null pointer exceptions in Java/C#, or segmentation faults in C and C++ are one of the biggest sources of runtime errors. Furthermore, there's no reason whatsoever that these problems can't be caught by the compiler in a strongly typed language like C++ that has the idea of a non-nullable pointer. The whole point of type annoations is to catch these errors before runtime after all. Otherwise it's just a lot of useless typing. C++ partially solves the problem partially with references, and truly static safe typed language like ML solve this problem by making variables typesafe by default, and using an Optional type to wrap nullable types.
So my question, is, as the successor to C++, how does D solve this problem? I'm looking through the D docs, that are a little sparse, but I'm not seeing any references to pointers that can't be nulled.
Brendan
More information about the Digitalmars-d
mailing list