Do we really need const?

Janice Caron caron800 at googlemail.com
Tue Sep 18 01:24:06 PDT 2007


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.

I think this is a neat idea, however it won't work unless the compiler
can also do const-checking. This is one more optimisation which having
const allows. (And const-by-default would make it obvious).

----

I have thought of a problem though. Under the scheme I outlined in a
previous post, it would no longer be possible for a function to modify
the original reference. That is:

class C;
C c;
f(c)

void f(ref C c)
{
    c = new C(); /* compile-time error */
}

would no longer compile, because under the new scheme, "ref" is
reinterpreted to mean that c is head-const (because C is a class - see
definitions in previous post). So instead, you'd have to do:

class C;
C c;
f(&c)

void f(ref C* c)
{
    *c = new C();
}

Whether or not that would be considered a prohibiting problem, I don't know.



More information about the Digitalmars-d mailing list