What's wrong with just a runtime-checked const?

Don Clugston dac at nospam.com.au
Thu Jul 20 05:37:15 PDT 2006


Bruno Medeiros wrote:
> Reiner Pope wrote:
>> Bruno Medeiros wrote:
>>>> Can you suggest another solution other than avoiding const-checking 
>>>> entirely? By the way, a dedicated string class is actually an 
>>>> implementation of runtime const checking.
>>>>> but, it's certainly not a pretty solution... and there's a related 
>>>>> question - how can tolower know whether to .dup or not.. there are 
>>>>> certainly cases where it isn't necessary.
>>>> This is just another issue that static checking can't solve but 
>>>> runtime checking can (providing we have a modification of the 
>>>> libraries to support a CoW and a in-place version).
>>>
>>> I'm not following you. That code example shows how a static const 
>>> checking should work, so what is the problem with that?
>>> And in:
>>>   char[] name_m = tolower(name);
>>>   // Can we modify name_m? Better dup it, just to make sure
>>> You ask if we can modify name_m, the answer is yes if the return type 
>>> of tolower is non-const, no if it const, so what's the issue here?
>>
>> You seem to have ignored my more recent example. The problem is that 
>> static checking *forces* the return value to be const, which in turn 
>> forces you to dup it. You don't always need to do that:
>>
>>  >> char[] tolower(const char[] input) /* the input must be const, 
>> because we agree with CoW, so we won't change it */
>>  >> {
>>  >>   // do some stuff
>>  >>   if ( a write is necessary )
>>  >>   { /* copy it into another variable, since we can't change input 
>> it's const)*/
>>  >>   }
>>  >>   return something; /* This something could possibly be input, so 
>> it also needs to be declared const. So we go back and make the return 
>> value of the function also a const. */
>>  >> }
>>  >>
>>  >> // Now, since the return value is const, we *must* dup it.
>>  >>
> 
> Are you saying that in that function, what is returned sometimes needs 
> do be const(readonly) and sometimes not? 

Yes.

And because of that the
> function needs to return const everytime?
> But then why not have the function return non-const and do the duping 
> when necessary?

Doesn't help.

Either, the function has to dup every time (even if the input was a 
const, and it's passing it on unmodified) -- so that a user of the 
function can write without copying first

OR the user of the function has to dup every time (even if it was 
already duped)

In both cases, you have an unnecessary dup.





More information about the Digitalmars-d-learn mailing list