Do we really need const?

Bill Baxter dnewsgroup at billbaxter.com
Tue Sep 18 01:57:05 PDT 2007


Janice Caron wrote:
> About passing structs by reference: It's one of those things, like
> register or inline...
> 
> Once upon a time, programmers used the keyword "register" because they
> thought they could do a better job than the compiler at figuring how
> to use its registers.
> 
> Once upon a time, programmers used the keyword "inline" because they
> thought they could do a better job than the compiler at figuring out
> what to inline and what not.
> 
> Now people explicitly choose between f(s) and f(ref s) (where s is a
> struct and the function does not modify it) because they think they
> can do a better job than the compiler at figuring out how to pass
> parameters to functions. I say give control back to the compiler. Lets
> let "ref" mean "the function may modify the parameter", and the
> absense of ref mean "the function may not modify the parameter", but
> leave it to the compiler to decide what is the most efficient way to
> pass the data to the function.

This thought has occurred to me before to.  I think issue becomes that 
the function signature may no longer enough for a compiler to tell what 
kind of code it needs to generate to call the function.  So for instance 
"pass by ref unless something in the function modifies the value" is not 
going to work.  But something like "pass by value unless the size of the 
parameter is greater than 8 bytes" could work.

I think this is a separate issue from explicitly passing things as 
'ref'.  The above seems more appropriate to me as an implementation of 
'in' parameters.

For compiling function bodies, if the compiler detects a modification of 
an 'in' parameter that it chose to implement using pass-by-reference 
then it would just generate code in the function body to copy the 
parameter value first first thing.  E.g.

void foo(in BigStruct x);

compiler actually generates code like:

void foo(ref BigStruc x) {
    ...
}

unless the body of foo modifies x.  Then the code gen changes to:

void foo(ref BigStruct x_) {
    BigStruct x = x_;
    ...
}


There would still be a bit of a compiler compatibility issue though. 
For a given platform Compiler vendors A and B would need to agree on the 
rules for 'in' parameters or the libs they generate would be 
incompatible.  If we want D to be a language with a unified ABI at 
least.  That suggests that the rules would need to be part of the spec. 
  Heck it may be good enough to just pick a max parameter size and stick 
with it for all platforms.  Just like D picks a size for 'float' and 
sticks with it for all platforms, whether it's the most efficient for 
that platform or not.

--bb



More information about the Digitalmars-d mailing list