References in D

Simen Kjaeraas simen.kjaras at gmail.com
Sat Sep 15 06:49:42 PDT 2012


On Sat, 15 Sep 2012 15:32:35 +0200, Maxim Fomin <maxim at maxim-fomin.ru>  
wrote:

> On Saturday, 15 September 2012 at 12:38:53 UTC, 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.
>
> Completely disagree. By the way, you are mixing references and classes.
> struct S {}
>
> void foo(ref S s); // cannot pass null pointer S* or null - "always  
> there"

void bar( ref int n ) {
     n = 3;
}

void main( ) {
     int* p = null;
     bar( *p );
}

Good luck.

Of course, it's not that obvious in production code, but I've had this
happen to me in C++, and - obviously - it can happen in D, too.

-- 
Simen


More information about the Digitalmars-d mailing list