Fully transitive const is not necessary

Janice Caron caron800 at googlemail.com
Sun Apr 27 08:53:40 PDT 2008


On 27/04/2008, Sean Kelly <sean at invisibleduck.org> wrote:
> what do they achieve that could not have been
> achieved via plain old const strings?

In a word: (OK - in three words): Copy On Write.

For example, one could write a function

    string escape(string s);

which escaped certain characters (by preceding them with '\' or
whatever). Because s is an array of invariant chars, if nothing needs
to be escaped, the function is able to return s.

This would not be possible with "plain old const strings". To
illustrate, suppose the declaration of the function had been

    const(char)[] escape(const(char)[] s);

Then:

    char[] s = "fixed".dup;

    auto t = escape(s);
    assert(t == "fixed");

    s[0] = 'm';
    assert(t == "fixed"); /* FAILS */


With invariant, it just works.



More information about the Digitalmars-d mailing list