Andrei Alexandrescu wrote: > Jason House wrote: >> 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" > > It does, and for a good reason - File stores an alias of it. If it > didn't have to, it would have accepted const, in which case a mutable > string would have sufficed.
I think you missed my point, but I was partly being a devil's advocate... I probably should not be fanning the flames for this thread, so I'll be quiet
