const?? When and why? This is ugly!

Walter Bright newshound1 at digitalmars.com
Sat Mar 7 22:23:04 PST 2009


Burton Radons wrote:
> 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.

What I interpret from this is that you see strings as fundamentally 
mutable character arrays, and sometimes in special cases you can make 
them immutable. I propose turning that view on its head - regard strings 
as fundamentally immutable, and having a mutable char array is a rare 
thing that only appears in isolated places in the program.

In the find() example, the implementation of it actually uses a mutable 
char[] to build the result. When the result is done, it is converted to 
immutable and "published" by returning it. The mutable array never 
escapes the function; it is completely sandboxed in.

What sold me on immutable strings was going through my code and looking 
to see where I *actually* was mutating the strings in place rather than 
just passing them around or storing them or copying them into another 
buffer. It turns out it was a vanishingly small number. I was startled. 
Not only that, those places could be, with a minor bit of refactoring, 
further reduced in number without sacrifice. I stacked this against the 
gain by eliminating all those places that were doing copies, and it was 
clear that immutable strings as default was a winner.



More information about the Digitalmars-d mailing list