const?? When and why? This is ugly!

Derek Parnell derek at psych.ward
Fri Mar 6 17:55:03 PST 2009


On Fri, 06 Mar 2009 18:25:13 -0500, jerry quinn wrote:

> 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?

Most of this discussion seems to assume that there is only two types of
data - immutable and mutable, but there is a third type - "potentially
mutable".

invariant(char)[] --> immutable 
                  --> Once set, it cannot be changed by anything.
const(char)[]     --> potentially mutable
                  --> The compiler ensure that the routine that declares 
                      this will not change it, but it can be changed by
                      other routines.
char[]            --> mutable
                  --> Anything can change this.


The alias "string" only refers to immutable stuff. Can we come up with
aliases for "potentially mutable" and "mutable" too?

I would argue that the parameter signature for my_find() needs to use the
"const(char)[]" type because that means that the coder and compiler says
that this function won't change the input but we don't particularly care if
the input is immutable, or mutable by something else.

-- 
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell



More information about the Digitalmars-d mailing list