Proposal for scoped const contracts

Steven Schveighoffer schveiguy at yahoo.com
Mon Mar 24 18:51:22 PDT 2008


"Edward Diener" wrote
> Steven Schveighoffer wrote:
>> This idea has come from the discussion on the const debacle thread.
>>
>> It is basically an idea for scoped const.  The main goal is so that one 
>> can specify that a function does not modify an argument without affecting 
>> the constness of the input.
>>
>> The main problem to solve would be that I have a function with an 
>> argument that returns a subset of the argument.  The easiest function to 
>> help explain the problem is strchr.  Please please do NOT tell me that my 
>> design is fundamentally unsound because you can return a range or pair, 
>> and then slice the original arg based on that pair.  There are other 
>> examples that cannot be solved this way, this is just the easiest to 
>> explain with.  Everyone who uses C should know about strchr:
>>
>> char *strchr(char const *source, char const *pattern);
>
> In C++, assuming you meant strstr, this is:

Yes, I did mean strstr, sorry about that.

>
> char const * strstr(char const *source, char const * pattern);
>
> I believe C++ has this right. I do not understand why D programmers want 
> to return a non-const from a const input, even in the face of D slicing.

According to online docs, it is sometimes const, sometimes not, sometimes 
both (2 versions, one in which both return and arg are const, one in which 
both are mutable).

The problem with your version is that it is not very useful for mutable 
strings.  If you wanted, for instance, to replace all instances of "hello" 
with "jello", in order to use strstr, you would need to either cast away 
const, or do pointer arithmetic with the result.

-Steve 





More information about the Digitalmars-d mailing list