preparing for const, final, and invariant

Daniel Keep daniel.keep.lists at gmail.com
Fri May 18 00:05:23 PDT 2007


Note: I've read the reply where you clarified that this is to allow
static things like string literals to be passed in.

Walter Bright wrote:
> This is coming for the D 2.0 beta, and it will need some source code
> changes. Specifically, for function parameters that are arrays or
> pointers, start using 'in' for them.
> 
> 'in' will mean 'scope const final', which means:
> 
> final - the parameter will not be reassigned within the function
> const - the function will not attempt to change the contents of what is
> referred to
> scope - the function will not keep a reference to the parameter's data
> that will persist beyond the scope of the function
> 
> For example:
> 
> int[] g;
> 
> void foo(in int[] a)
> {
>     a = [1,2];    // error, a is final
>     a[1] = 2;   // error, a is const
>     g = a;    // error, a is scope
> }
> Do not use 'in' if you wish to do any of these operations on a
> parameter. Using 'in' has no useful effect on D 1.0 code, so it'll be
> backwards compatible.

Is final really necessary?  I can understand const and scope; but is it
really a problem if the function rebinds the argument?  I mean, that
shouldn't affect the calling code in the slightest, should it?

void foo(const scope int[] a)
{
    a = [1,2];
}

static bar = [3,4];
foo(bar);
assert( bar == [3,4] ); // This should still hold, right?

There are a few functions I've written which re-bind the argument as
they run; the simplest examples being functions that process strings
(effectively, it just loops until there's just an empty slice left).

Apart from that, I don't think there's any problems with doing this.  Oh
well; I'll just have to declare an extra argument.  :P

> Adding in all those 'in's is tedious, as I'm finding out :-(, but I
> think the results will be worth the effort.

Actually, I was thinking of doing this anyway so that my argument lists
are nice and symmetric (qualifiers on all of them, instead of just ref
and out).  Now I have an excellent reason to do so other than my
pedantic-ness. :)

One question: is there a keyword for "normal" arguments--for instance, I
know that most variables are "auto" if you don't specify the storage
class explicitly.  I can't imagine where it would be useful; just curious.

At any rate, looks spiffy.

	-- Daniel

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/



More information about the Digitalmars-d-announce mailing list