References in D
Alex Burton
alexibu
Thu Oct 4 04:14:00 PDT 2012
On Saturday, 15 September 2012 at 21:30:03 UTC, Walter Bright
wrote:
> On 9/15/2012 5:39 AM, Henning Pohl wrote:
>> The way D is dealing with classes reminds me of pointers
>> because you can null
>> them. C++'s references cannot (of course you can do some nasty
>> casting).
>
> Doing null references in C++ is simple:
>
> int *p = NULL;
> int& r = *p;
>
> r = 3; // crash
IMHO int * p = NULL is a violation of the type system and should
not compile.
NULL can in no way be considered a pointer to an int.
In the same way this should fail:
Class A
{
}
A a;
Low level programmers might know that references are implemented
in the microprocessor as memory locations holding addresses of
other memory locations, but high level programmers should not
need to know this.
A separate special syntax should be used by low level code in D.
In the vast majority of code, having nullable references is a
source of bugs.
Passing null to a function expecting a reference/pointer to
something is equivalent to passing a random number and is the
same as mixing a biycle into a recipe asking for a cup of sugar.
In cases where you really want to pass a value that could be a
reference to something or could be null, use a special type that
allows this.
A clever library writer might be able to implement such a type
using their low level knowledge of pointers but the rest of us
should be protected from it.
More information about the Digitalmars-d
mailing list