string is rarely useful as a function argument

bearophile bearophileHUGS at lycos.com
Wed Dec 28 05:27:56 PST 2011


Peter Alexander:

> Any time you want to create a string without allocating memory.
> 
> char[N] buffer;
> // write into buffer
> // try to use buffer as string

I have discussed a bit two or three times about this topic. In a post I even did suggest the idea of "scoped immutability", that was not appreciated. Generally creating immutable data structures is a source of troubles in all languages, and in D it's not a much solved problem yet.

In D today you are sometimes able to rewrite that as:

string foo(in int n) pure {
    auto buffer = new char[n];
    // write into buffer
    return buffer;
}
void bar(string s) {}
void main() {
    string s = foo(5);
    bar(s); // use buffer as string
}

Bye,
bearophile


More information about the Digitalmars-d mailing list