const?? When and why? This is ugly!
Sergey Gromov
snake.scaly at gmail.com
Sat Mar 7 18:24:22 PST 2009
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.
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.
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.
More information about the Digitalmars-d
mailing list