const by default.

Sean Kelly sean at f4.ca
Tue Jul 4 09:43:35 PDT 2006


Deewiant wrote:
> BCS wrote:
>> However if you are passing them to a function they become implicitly
>> immutable unless you say otherwise. (Assume that "@" is the grant
>> mutability operator)
>>
>> void fn4()
>> {
>>     char[] c;
>>
>>     c[5] = '\0';    // allowed
>>
>>     fn1(c);        // allowed
>>     fn2(c);        // not allowed: arg 1 is mutable;
>>     fn2(@c)        // allowed
>> }
>>
>> In the general case I expect that this change will have little effect on
>> code. In my experience, most pass by reference cases are immutable
>> anyway. The rest should be easy to find and fix as long as DMD gives
>> good error messages.
> 
> I think there's a problem with all this "grant mutability/immutability", which
> is that we're just degenerating into C++ with its const_cast. With it, the
> compiler has few, if any, guarantees about the constness of anything --- it can
> always be casted away.
> 
> The way I see it, something either is or isn't mutable, and it should stay that
> way for the duration of the program --- in some cases, for the duration of a
> function or the lifetime of an object.

I think the issue is to find a balance between clarity and elegance.  On 
the surface, const as default would suggest the need to qualify nearly 
all local variables as 'mutable'.  But if the issue really is enforcing 
call contracts for function parameters and return values, as well as 
loop invariant optimization, then perhaps const-ness could be limited to 
these areas as well?  For example, it should only be necessary to 
qualify reference types as 'mutable' as everything else is passed by 
value anyway.  I am coming to think that 'in' vs. 'inout' may be 
sufficient to distinguish intent for function parameters, which leaves 
return values and declarations.  I can't say I'm entirely happy with the 
idea of using 'mutable' all over the place for declarations even though 
it would probably be easiest.  In some respects I'd rather leave 
declarations as-is and "mutable" qualify variables at the point of use:

     MyClass fn( MyClass c, inout MyClass d ) {}

     MyClass a, b;

     inout MyClass e = fn( a, inout b ); // error

But I'll admit to not being entirely happy with this syntax either.


Sean



More information about the Digitalmars-d mailing list