Extended Type Design: further examples

Sean Kelly sean at f4.ca
Mon Mar 19 15:20:56 PDT 2007


Andrei Alexandrescu (See Website For Email) wrote:
> 
> By the way, a couple of days ago I've had an idea. Many people here ask
> for a "string" alias because char[] is a tad hard to type and uneasy on
> the eyes. Probably a good candidate would be:
> 
> alias invariant char[] string;
> 
> The resulting type is pretty damn slick:
...
> 3. The ~= operator works (somewhat surprisingly).

I assume this is because a char[] is actually a struct containing a 
pointer, so 'invariant' allows that pointer to be reassigned--it simply 
protects the referenced string?  This is the sticking point for me. 
Assume we have this:

     struct Foo
     {
         int  x;
         int* y;
     }

     const Foo foo; // is this legal?
     foo.x  = 1;    // this is allowed
     *foo.y = 2;    // this is not allowed

Is that correct, or do 'const' and 'invariant' truly only apply to pure 
reference types?

> 4. It's very, very rare that you want to modify some random character in
> a string, and when you do, use a char[] and then copy it back into a
> string, or rebuild the string from slices!

This may be true for a string, but for arrays in general I think this is 
fairly common.

> 5. The Java experience (where String is immutable and StringBuffer is
> the mutable, build-me-piecemeal object) turned out to be largely
> successful, modulo syntax details that are not so elegant.
> 
> 6. It meshes great with literals, which are exactly invariant arrays of
> characters:
> 
> string hi = "Hello!"; // no dup needed! And it's 100% safe!
> 
> So it looks like we have solved the string issue in an unexpectedly
> elegant way - by simply combining two features: invariant and array.

Agreed.  This is pretty nice :-)


Sean



More information about the Digitalmars-d mailing list