char[] to string

Jonathan M Davis jmdavisProg at gmx.com
Sat Jun 11 12:29:15 PDT 2011


On 2011-06-11 05:12, bearophile wrote:
> Jonathan M Davis:
> > Even better though, would be to use std.conv.to - e.g. to!string(input).
> > This will convert input to a string, but it has the advantage that if
> > input is already a string, then it'll just return the string rather than
> > making another copy like idup would.
> 
> I didn't know this. Isn't it very good to give this bit of intelligence to
> idup too?

Except that if you actually need it to create a copy for some reason, then 
it's a lot harder. However, to!() goes far beyond just improving idup anyway, 
because to!() should always be avoiding doing conversions if they're not 
actually necessary. So, if you trying to convert to char[] or const(wchar)[] 
or whatever, if no conversion is actually necessary, then the original 
argument will be returned. It doesn't matter what the original argument was. 
dup and idup only cover the case where you're trying to explicitly copy an 
array, whereas to!() covers any time that you're trying to convert to one to 
another type. So, it's generally best to use dup and idup only when you 
definitely want to make a copy. By using them, you're explicitly stating that 
you _want_ a copy to be made. If you just want a conversion, then to!() will 
do the trick in what is hopefully the most efficient way possible.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list