string is rarely useful as a function argument

Jonathan M Davis jmdavisProg at gmx.com
Wed Dec 28 12:43:41 PST 2011


On Wednesday, December 28, 2011 10:27:15 Andrei Alexandrescu wrote:
> I'm afraid you're wrong here. The current setup is very good, and much
> better than one in which "string" would be an alias for const(char)[].
> 
> The problem is escaping. A function that transitorily operates on a
> string indeed does not care about the origin of the string, but storing
> a string inside an object is a completely different deal. The setup
> 
> class Query
> {
>      string name;
>      ...
> }
> 
> is safe, minimizes data copying, and never causes surprises to anyone
> ("I set the name of my query and a little later it's all messed up!").
> 
> So immutable(char)[] is the best choice for a correct string abstraction
> compared against both char[] and const(char)[]. In fact it's in a way
> good that const(char)[] takes longer to type, because it also carries
> larger liabilities.
> 
> If you want to create a string out of a char[] or const(char)[], use
> std.conv.to or the unsafe assumeUnique.

Agreed. And for a number of functions, taking const(char)[] would be worse, 
because they would have to dup or idup the string, whereas with 
immutable(char)[], they can safely slice it without worrying about its value 
changing.

I think that if we want to make it so that immutable(char)[] isn't forced as 
much, then we need to make proper use of templates (which also can allow you 
to not force char over wchar or dchar) and inout - and perhaps in some cases, 
a templated function could allow you to indicate what type of character you 
want returned. But in general, string is by far the most useful and least 
likely to cause bugs with slicing. So, I think that string should remain 
immutable(char)[].

- Jonathan M Davis


More information about the Digitalmars-d mailing list