Andrei Alexandrescu Wrote: > Sergey Gromov wrote: > > Sat, 07 Mar 2009 15:19:50 -0800, Andrei Alexandrescu wrote: > > > >> To recap, if an API takes a string and all you have a char[], DO NOT > >> CAST IT. Call .idup - better safe than sorry. The API may evolve and > >> store a reference for later. Case in point: the up-and-coming > >> std.stdio.File constructor initially was: > >> > >> this(in char[] filename); > >> > >> Later on I decided to save the filename for error message reporting and > >> the such. Now I had two choices: > >> > >> (1) Leave the signature unchanged and issue an idup: > >> > >> this.filename = to!string(filename); // issues an idup > >> > >> (2) Change the signature to > >> > >> this(string filename); > >> > >> Now all client code that DID pass a string in the first place (the vast > >> majority) was safe _and_ efficient. The minority of client code was that > >> that had a char[] or a const(char)[] at hand. That code did not compile, > >> so it had to insert a to!string on the caller side. > >> > >> As has been copiously shown in other languages, the need for > >> character-level mutable string is rather rare. So most of the time you > >> will not traffic in char[], but instead you'll have a immutable(char)[] > >> to start with. This further erodes the legitimacy of your concern. > > > > My file names are constructed most of the time. And most of the time > > they are simple char[]s. > > Ehm. Mine are also constructed, but somehow come in string format, e.g.: > > string basename; > ... > auto f = File(basename ~ ".txt"); > > > It is not obvious that File should store the file name. It's not > > strictly necessary. It's an *implementation detail.* Now you expose > > this implementation detail through the class interface, and you do this > > without any good reason. You save a 150 byte allocation per file. > > Nice. > > It's just an example, the point being that there things are always fast > and safe. In many cases there's much more at stake and you can't rely on > idioms that allocate memory needlessly.
Your example above does allocate memory. A mutable string could potentially avoid allocating to append ".txt" > > I can understand when a hash takes an immutable key. It's in the hash's > > contract. Various lazy functions could take immutable input to > > guarantee correct lazy execution. But I think that overall use of > > immutable types should be rare and thoroughly thought-out. They should > > be used only when it's absolutely, provably necessary. That's why I > > think aliasing string as immutable is a mistake. It felt wrong when I > > discovered D a year ago, and it feels wrong now. > > That may be because you are writing C in D. Immutable strings should > allow solid coding without much friction. > > > Andrei
