References in D

Simen Kjaeraas simen.kjaras at gmail.com
Sat Sep 15 07:16:45 PDT 2012


On Sat, 15 Sep 2012 14:39:49 +0200, Henning Pohl <henning at still-hidden.de>  
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.

Let's start by defining the different types of references D has:

1) Parameter storage class 'ref'. Used when passing an argument by
    reference. Example:
       void foo(ref int n);

2) Class references. Used whenever you have a class. Example:
       auto a = new MyClass();

3) Ref return. Kinda like #1, but for return values. Example:
       ref int bar( );

4) Pointers. Yeah, they're a kind of reference, with the internal
    workings all laid out for anyone to see. Example:
        int* p = new int;

5) Template alias parameters. Let's ignore those for this discussion.

6) Smart pointers of various kinds. Also ignorable for this discussion.

Now, you want #2 to work more like #1, right?

#2 works in some ways like pointers(#4). Most notably, you can have a null
class reference. It's only lately we have gotten support in the language  
for
disabling default constructors of structs (and there are still bugs with
that), allowing non-null pointers and references to be implemented in the
library.

The reason for that can be explained mostly in that Walter did not believe
non-nullable references were that important. The reason it has not become
the default as his understanding has come, is probably because it would be
a very disruptive change of the language, and break *all* code ever written
in D.

Perhaps in D3, though.

-- 
Simen


More information about the Digitalmars-d mailing list