string to char*

bearophile bearophileHUGS at lycos.com
Sun Sep 12 05:24:19 PDT 2010


Jonathan M Davis:
> Well, if you look at toStringz()'s implementation, you may notice that there's 
> commented out code which would not make a copy if there's a 0 in memory one 
> passed the end of the string. It would simply use that 0 as the end of the const 
> char* and avoid the copy. That being the case, it avoids a copy but must be 
> const, because the string is immutable.

I see, thank you for the answer. Generally in the C code that uses the C string I can't be certain that it doesn't modify the string. On the other hand often I need a char* and not a const char*. Ao I'd like toStringz() to always copy and return a char* (Often I need a const pointer to mutable chars).

Another possibility is to have two functions, one that always performs the copy and returns a char*, and one that sometimes doesn't copy and returns a const char*.

Or a single template function that returns a const char* if doconst is true :-)
auto toStringz(bool doconst=false)(string s) { ...

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list