References in D

Alex Rønne Petersen alex at lycus.org
Sat Sep 15 05:44:20 PDT 2012


On 15-09-2012 14:39, 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). So you can be sure to have a valid well-defined object. But
> then there is always the ownership problem which renders them more
> dangerous as they seem to be. D resolves this problem using a garbage
> collector.
>
> So why not combine the advantages of C++ references "always there"
> guarantee and D's garbage collector and make D's references not
> nullable? If you want it to be nullable, you can still make use of real
> pointers. Pointers can be converted to references by implicitly do a
> runtime check if the pointer is not null and references can be converted
> back to pointers.
>
> I guess you had good reasons about choosing the nullable version of D
> references. Explain it to me, please.

D references are not like C++ references *at all*. Reference types in D 
are always classes - no exceptions. When you just need to pass something 
by reference down the call stack and be sure you have no null 
references, you can use 'ref'.

But this being said, I agree that references being nullable by default 
is hurtful. It allows any object reference to have an invalid state even 
though in 99% of cases, that doesn't make sense. It's a giant hole in 
the type system that many new languages have gotten rid of very early 
(forcing the programmer to use explicit option/nullable types).

The way references work in D is pretty much inherited from Java/C#.

http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare

Anyway, it's too late to change it now.

-- 
Alex Rønne Petersen
alex at lycus.org
http://lycus.org


More information about the Digitalmars-d mailing list