What if D would require * for reference types?

Steven Schveighoffer schveiguy at yahoo.com
Mon Jan 18 12:27:05 PST 2010


On Mon, 18 Jan 2010 15:08:56 -0500, Lars T. Kyllingstad  
<public at kyllingen.nospamnet> wrote:

> Steven Schveighoffer wrote:
>> I think conversion from a reference to a pointer should be available  
>> via a cast, but I'm not sure whether the compiler should allow class  
>> pointers.  My gut feeling is no.
>
> Isn't this already possible?
>
>    class Foo { }
>
>    Foo foo = new Foo;
>    Foo* ptr = cast(Foo*) foo;
>
>    // ptr is not a pointer to the reference.
>    assert (ptr != &foo);

Hm.. does ptr actually work though?  My guess is it would not.

i.e. I think this would not work:

class Foo
{
    int x;
    void bar() { writefln(x); }
}

Foo foo = new Foo;
foo.x = 42;
Foo* ptr = cast(Foo*) foo;

ptr.bar();  // I predict at least that it does not print 42, possibly it's  
a crash.

The reason is because Foo* means "a pointer to a reference to a Foo."   
This is the whole problem with builtin references, you can't get at the  
type without including the reference.

>
>
>> Are there any syntax ambiguities here?  & is also a binary op, but then  
>> again, so is *.  Will there be an issue with && ? I mean, because the  
>> references are rebindable, you should be able to have a reference to a  
>> reference.
>>  Also, struct references in this way will be usable in safe D, enabling  
>> heap struct data!
>>  The more I think about it, the more I like having an explicit  
>> reference denotation for classes, with the compiler enforcing that you  
>> simply can't use class data as a value type.  This basically makes all  
>> the tail-X syntax just work, and still retains the benefits of classes  
>> being reference-only types.  The tail shared problem is a really crappy  
>> issue, worse than tail-const.
>
> I like it too. :) But I'm not sure we should use the & symbol:
>
>    Foo& foo = new Foo;     // & denotes a reference
>    Bar* bar = &barValue;   // & returns a pointer
>
> Yes, C++ does it, but it's still ugly.

C++ is quite different, C++ uses & to denote the same thing as ref does in  
D, except you can declare them wherever, not just in parameter lists.

i.e.:

Foo foo, other;
Foo& foo2 = foo;  // one and only time you can bind foo2
foo2 = other; // equivalent to saying foo = other, does not rebind foo2.

Foo& foo3 = new Foo; // Error, new Foo returns a pointer, cannot assign to  
a reference

The second line you have there is a bit troubling.  I agree it doesn't  
look very good.  Note that we already live with * having three meanings --  
denoting a pointer, dereferencing a pointer, and multiplication.  In all 3  
cases the syntax is unambiguous, but the meaning isn't so clear to a  
person reading it.  It's roughly the same as & would be.  I wonder if  
there are better symbols?

Foo$
Foo%
Foo#

-Steve



More information about the Digitalmars-d mailing list