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?

The answer is to encourage the use of immutable strings. I believe the future of programming will tend towards ever more use of immutable data, as immutable data:

1. is implicitly sharable between threads
2. is more conducive to static analysis of programs
3. makes it easier for programmers to understand code
4. enables better code generation
5. allows taking a private reference to without needing to make a copy

const(char)[], on the other hand, still leaves us with the temptation to make a copy "just in case". If I, as a user, sees:

int foo(const(char)[] s)

what if foo() keeps a private reference to s (which it might if it does lazy evaluation)? Now I, as a caller, mutate s[] and muck up foo. So, to fix it, I do:

foo(s.dup);    // defensive copy in case foo keeps a reference to s

But the implementor of foo() doesn't know it's getting its own private copy, so the first line of foo() is:

int foo(const(char)[] s)
{
    s = s.dup;   // make sure we own a copy
}

so the defensive, robust code has TWO unnecessary copies.

Reply via email to