downs Wrote:

> Walter Bright wrote:
> > Jeremie Pelletier wrote:
> >> Isn't it possible to make 'const ref S' or 'in S' generate the same
> >> machine code as 'in S*'? To me it would seem the semantics of the two
> >> are the same, with 'const S*' being useful syntax for C compatibility
> >> while 'in S' and 'const ref S' are both D syntax.
> > 
> > The thing about const is it only specifies a read only view of an
> > object, it does *not* specify that the referenced object will not
> > change. That is why pass by value cannot be "optimized" to be pass by
> > reference.
> > 
> 
> To elaborate on this, consider this case:
> 
> import std.stdio;
> 
> struct X { int v; }
> 
> void test(X x, void delegate() dg) { writefln(x.v); dg(); writefln(x.v); }
> 
> void main() {
>   X ecks;
>   test(ecks, { ecks.v = 17; });
> }

Ok, I understand why it cant be done for 'in S' but I don't see why 'const ref 
S' cannot have the same semantics as 'in S*', unless 'ref' doesn't mean that 
the struct is implicitly dereferenced.

Here is some code to illustrate my point of view:

struct S { int i; }
S s;

void Stuff() { s.i++; }

void Foo(in S* s) {
    writefln(s.i);
    Stuff();
    writefln(s.i);
}
void Bar(const ref S s) {
    writefln(s.i);
    Stuff();
    writefln(s.i);
}

int main() {
    // Those both do the exact same thing
    Foo(&s);
    Bar(s);
}

If they are meant to have different semantics, then when is a good time to use 
ref? It would seem to me 'in S*' and 'S*' carry both behaviors you want in a 
referenced parameter: const and mutable. In any case only the reference is 
passed by value, not the struct itself.

If the method calls another method which modifies the const view on the 
reference, then it should be a logic error from the programmer (good old 
shooting yourself in the foot) without the compiler getting in the way. Making 
fool-proof language semantics is a good idea, but IMO it shouldn't impact 
performance, or else any bit of code looking for time critical performance will 
never use the syntax that makes D shine, and a lot of confusion will spread 
around as both types of syntax are used. It also makes it confusing to 
interface with IDL.

Alls I'm suggesting is that 'const ref S' and 'ref S' generate the same machine 
code as 'in S*' and 'S*', which would prevent us from using different syntax to 
get the performance boost, when in the end the intended behavior is the same.

Reply via email to