Why can't we make reference variables?

Tommi tommitissari at hotmail.com
Tue Aug 28 18:16:20 PDT 2012


On Wednesday, 29 August 2012 at 00:34:02 UTC, cal wrote:
> On Wednesday, 29 August 2012 at 00:21:29 UTC, Tommi wrote:
>> In this situation, I think, the most convenient and sensible 
>> thing to do is to make a reference to the data, and use that 
>> reference multiple times. We could make a pointer, but then 
>> we'd be stuck with the nasty syntax of dereferencing:
>
> This works currently:
>
> struct Test
> {
>     void foo() const
>     {
>         writeln("FOO");
>     }
> }
>
> void main()
> {
>     immutable(Test)* ptr = new immutable(Test);
>     ptr.foo();
> }

Now, that's a surprise for someone coming from C++. But even 
though ptr looks like a reference variable in your example, it 
doesn't look like it at all in this example:

void main()
{
     int counter = 0;

     auto notQuiteRefCounter = &counter;

     // Increments the pointer, not counter value
     ++notQuiteRefCounter;

     // Can't do this
//  int counterBackup = notQuiteRefCounter;

     // Prints deref: 0   no-deref: 18FD34
     writefln("deref: %s  no-deref: %s",
              *notQuiteRefCounter,
               notQuiteRefCounter);
}


More information about the Digitalmars-d mailing list