pointers, functions, and uniform call syntax

Carl Sturtivant sturtivant at gmail.com
Mon Sep 3 08:12:08 PDT 2012


> I thought "this should have zero impact, because in D, because 
> "." is supposed to deference for you if needed."

D can't do this all the time: struct pointer assignment for 
example, should not automatically cause the corresponding structs 
to be assigned.

> ----
> struct S
> {
>   void foo();
> }
> void bar(S);
>
> void main()
> {
>   auto r = new S;
>   r.foo();
>   bar(r);  //derp
>   r.bar(); //derp
> };
> ----
> I find it strange, because I thought the entire point was to 
> abstract way something was allocated to the way it was used: 
> EG. From a caller perspective, I don't care if r is on the 
> stack or on the heap: I just want to call the method bar on the 
> object in question.

bar(r) would need D to support an implied conversion of S* to S 
(or to ref S with bar having a reference parameter if you wanted 
to avoid copying), for this to work.

Converting S* to ref S (without copying) is an interesting idea 
for D. I wonder what those close to the definition of D and the 
compiler think of it.

> Things get even stranger if you mix in uniform call syntax. 
> "r.foo()" works, but "r.bar()" doesn't?
>
> Am I really forced into:
> ----
> struct S
> {
>   void foo();
> }
> void bar(S);
> void main()
> {
>   auto r = new S;
>   r.foo();
>   bar(*r);    //Groan
>   (*r).bar(); //Super Groan.
> };
> ----
> I feel as if I'm just back at square 1...

You could fake it: D has 'alias this' which helps a lot.

#!/usr/bin/rdmd

import std.stdio;

struct Sdata {
   int x[10000]; //imagine this inline in the struct
   this(this) { writeln("Copied!"); }
   void foo() { writeln("foo: ", x[99]); }
}

struct S {
   Sdata* ptr;
   alias ptr this;
   this(Sdata* newSdata) { ptr = newSdata; }
}

ref int bar(S s) { s.x[99] = 3142; return s.x[99]; }

void main() {
   auto r = S(new Sdata);
   bar(r);
   writeln("main: ", r.x[99] );
   r.bar = 999;
   writeln("main: ", r.x[99] );
   r.foo();
}




More information about the Digitalmars-d mailing list