References in D

Alex Burton alexibureplacewithzero at gmail.com
Thu Oct 4 23:45:31 PDT 2012


On Friday, 5 October 2012 at 04:50:18 UTC, Jonathan M Davis wrote:
> On Friday, October 05, 2012 05:42:03 Alex Burton wrote:
>> I realise what is currently the case I am making an argument as
>> to why I this should be changed (at least for class references 
>> in
>> D).
>
> This was talking about C++ references, not D, giving an example 
> of how they
> can be null even though most people think that they can't be. 
> int& isn't even
> legal syntax in D.

I was talking about both. Regardless of whether the int& 
reference or the int * reference was used to assign to memory 
address 0 in Walters example the result is still a crash and will 
be in D with equivalent code using explicit pointers or instances 
of classes (which are always pointers in D).

The crash is a result of two mistakes:

One is the language designer allowing null to be an acceptable 
value for a pointer to an int.
As should be blatently obvious that null is not a pointer to an 
int, but for historical reasons inherited from C (when people 
were just happy to get out of assembly language) it has been 
allowed.

The second mistake is that someone chose to use the language 
feature which clearly makes no sense.
This is bad programming for two reasons:
1) It is logically incorrect to state that 0 is a pointer to 
something.
2) It is a case of using magic numbers in code - an antipattern. 
It is trying to create some universal consensus that the magic 
number 0 means something special. What I am supposed to do with a 
null pointer is not so universal.
Do I construct it ? Do I throw an exception ? Why on earth has 
someone sent me this 0 when my type system specifies I want a 
pointer to an int ?

> Regardless, references in D will _never_ be non-nullable. It 
> would break too
> much code to change it now regardless of whether nullable or 
> non-nullable is
> better.

I don't think this argument is any more powerful than any of the 
other 'lets remain compatible with C to avoid breakage' ones.

If it were changed there could be compiler errors for 
uninitialised references, and tests for null. These sorts of 
compile time errors are much more preferable than undefined 
behaviour in released code that crashes IMHO.

Alex



More information about the Digitalmars-d mailing list