const?? When and why? This is ugly!

Burton Radons burton.radons at gmail.com
Sat Mar 7 20:04:07 PST 2009


Walter Bright Wrote:

> If I may restate your case, it is that given function that does 
> something with character arrays:
> 
> int foo(string s);
> 
> and you wish to pass a mutable character array to it. If foo was 
> declared as:
> 
> int foo(const(char)[] s);
> 
> then it would just work. So why is it declared immutable(char)[] when 
> that isn't actually necessary?

No, that's not the problem at all. The problem is this line in object.d:

    alias invariant (char) [] string;

There are two interesting features here. It's what D calls a string, and it's invariant, making the declaration that whoever has a reference to that string can hold onto it forever without ever expecting its contents to be modified or destroyed.

So, while building my string I use a function which replaces matching substrings in a string with another string. If that function were to declare my parameters as strings they'd do two things: they'd tell the reader that its parameters can never change over the course of the program because it may retain copies of the parameters. That is a strong, highly prescriptive statement. So I would expect the function to be implemented like this:

   const (char) [] replace (const (char) [] s, const (char) [] from, const (char) [] to)

But it's not. std.string.replace is implemented like this:

   string replace (string s, string from, string to)

This is for a number of reasons. It's easiest to assume that the default is going to be the correct one. The const syntax is hard to read, so it's avoided, and "string" is more readily descriptive than "const (char) []". So, I pass my mutable string to std.string.replace, which only accepts invariant data.

This wouldn't be too bad because const is worthless when optimising, but if invariant is going to be given any weight then we must never cause data to be casted to invariant unless if it's actually invariant data. So, the sensible default is "const (char) []" for strings, a selection of aliases in object.d for the others, and safe casting templates in object.d.



More information about the Digitalmars-d mailing list