const?? When and why? This is ugly!

jerry quinn jlquinn at optonline.net
Fri Mar 6 15:25:13 PST 2009


Andrei Alexandrescu Wrote:

> Steven Schveighoffer wrote:
> > I think what Burton is saying is by annointing immutable(char)[] as the 
> > type "string," you are essentially sending a message to developers that 
> > all strings should be immutable, and all *string parameters* should be 
> > declared immutable.  What this does is force developers who want to deal 
> > in const or mutable chars have to do lots of duplication or casting, 
> > which either makes your code dog slow, or makes your code break const.
> > 
> > Evidence is how (at least in previous releases) anything in Phobos that 
> > took an argument that was a utf8 string of characters used the parameter 
> > type "string", making it very difficult to use when you don't have string 
> > types.  If you want to find a substring in a string, it makes no sense 
> > that you first have to make the argument invariant.  a substring function 
> > isn't saving a pointer to that data.
> > 
> > I think the complaint is simply that string is defined as immutable(char)
> > [] and therefore is promoted as *the only* string type to use.  Using 
> > other forms (such as in char[] or const(char)[] or char[]) doesn't look 
> > like the argument is a string, when the word "string" is already taken to 
> > mean something else.
> > 
> > -Steve
> 
> I see. Phobos is being changed to accept in char[] instead of string
> wherever applicable. As far as what the default "string" ought to be,
> immutable(char)[] is the safest of the three so I think it should be that.

So far this discussion has no examples.  Let me toss one out as a dart board to see what folks think:

char[] s = get_some_data();  // accesses a large buffer that i don't want to copy
size_t pos = my_find(s, "blah");
s[pos] = "c";

string s2 = "another string";
size_t pos2 = my_find(s2, "blah");
another_func(s2[pos2 .. pos2+4]);

size_t my_find(string haystack, string needle)
{
  // Perform some kind of search that is read-only
}

another_func(string s) {}

---

It seems like string is the obvious parameter type to use for my_find, but it doesn't work because we're passing mutable data in.  Instead we have to use const(char)[], which is less intuitive and uglier.

Or did I miss the thrust of the argument?





More information about the Digitalmars-d mailing list