string vs. const(char)[] on the function signature

Jonathan M Davis jmdavisProg at gmx.com
Fri Jul 13 11:40:36 PDT 2012


On Friday, July 13, 2012 10:19:34 Ali Çehreli wrote:
> QUESTIONS:
> 
> What do you think about all of this? Can you see better idioms? Should
> we simply ignore this issue and stick with immutable anyway, especially
> for strings since they are everywhere? Should the original foo() take
> string and have the callers make a copy if the original variable is mutable?

In a lot of cases, the answer is to simply template on string type so that you 
don't care. In other cases, you're going to need a string anyway, so why 
bother templatizing (e.g. you need to assign the string to a member variable 
or pass it to a C function)? And in some cases, there's no real gain in taking 
anything other than string.

It was debated for std.file whether it should take anything other than string, 
and we stuck with string, because it just wasn't worth bothering with anything 
else. Any string-related costs were nothing in comparison to the I/O going on, 
and whether string or wstring was what was needed for calling the C functions 
depended on the OS. So, we just stuck with string.

I believe that std.net.curl ends up using a combinatin of const(char)[] and 
string depending on what the string is ultimately used for.

std.path and std.string on the other hand templatize everything so that they 
work with any string type, but they're operating on strings and returning 
them, not saving them or using them with other APIs (let alone C APIs).

In general, I would argue that if you're going to operate on a string and then 
return it, you should templatize on string type (or even use a range, if the 
funciton can be genericized beyond strings). But in cases where you're going 
to need a specific string type, it's often best to just take that string type 
(usually string). In some of those cases though (particularly if you're going 
to have to copy it anyway), taking const(char)[] makes more sense. Classes are 
one case where you're likely to be forced to take either string or const(char)
[], because you can't templatize virtual functions.

So, ultimately, what makes the most sense depends entirely on the situation. 
I'm not sure that we can really give any hard and fast rules. It mostly comes 
down to balancing flexibility and performance. We should make functions as 
flexible as possible with regards string type but restrict it when it makes 
sense to do so for performance or when the extra flexibility just isn't 
warranted (or isn't possible - e.g. virtual functions).

You make very good points overall, and I think that you understand the 
situation fairly well, but I don't know how we'd really go about giving 
much in the way of concrete guidelines, since it's so situation-dependent.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list