Is all this Invarient **** er... stuff, premature optimisation?

Sean Kelly sean at invisibleduck.org
Mon Apr 28 10:48:29 PDT 2008


== Quote from Janice Caron (caron800 at googlemail.com)'s article
> 2008/4/28 Steven Schveighoffer <schveiguy at yahoo.com>:
> >  > I have some strings read in from external source that I need to convert to
> >  > uppercase. A quick look at Phobos and I find std.string has a toupper
> >  > method.
> >  > <very good example case removed>
> >
> >  This is all not an issue if Walter adopts 'scoped const' contracts.
> toupper() couldn't be reused for all constancies, because the
> invariant version should employ copy-on-write, wheras any other
> versions would not be able to do this.
> That is,
>     toupper("HELLO");
> can return the original, if and only if the string is invariant.

Can you explain this in light of Steven's 'scoped const' proposal?  By my
understanding (assuming scoped const):

    string bufI = "HELLO";
    char[] bufM = "HELLO".dup;
    const(char)[] bufC = bufM;

    string retI = toupper( bufI ); // return value is invariant - ok
    char[] retM = toupper( bufM ); // return value is mutable - ok
    const(char)[] retC = toupper( bufC ); // return value is const - ok
    const(char)[] retC2 = toupper( bufI ); // return value is invariant - ok

    bufM[0] = 'J';
    assert( retC[0] == 'J' );

The above seems perfectly fine, because it's impossible to pass a mutable
array and return a const reference to it--the return value will be mutable as
well.

By contrast, let's assume the invariant implementation:

    string toupper( string buf );

    char[] buf = "HELLO".dup;

    toupper( buf ); // fails
    toupper( buf.idup ); // works
    toupper( assertUnique( buf ) ); // works

In the first case I have to copy buf to pass it to toupper, and in the second I have
to perform a cast operation (albeit wrapped in a function to hide the truth).
Assuming for a moment that mutable strings are useful and so I won't be able to
use the 'string' alias all the time, can you explain what is good about either of
these scenarios?


Sean



More information about the Digitalmars-d mailing list