string types: const(char)[] and cstring

Reiner Pope some at address.com
Sun May 27 16:58:29 PDT 2007


Walter Bright wrote:
> Under the new const/invariant/final regime, what are strings going to be 
> ? Experience with other languages suggest that strings should be 
> immutable. To express an array of const chars, one would write:
> 
>     const(char)[]
> 
> but while that's clear, it doesn't just flow off the keyboard. Strings 
> are so common this needs an alias, so:
> 
>     alias const(char)[] cstring;
> 
> Why cstring? Because 'string' appears as both a module name and a common 
> variable name. cstring also implies wstring for wchar strings, and 
> dstring for dchars.
> 
> String literals, on the other hand, will be invariant (which means they 
> can be stuffed into read-only memory). So,
>     typeof("abc")
> will be:
>     invariant(char)[3]
> 
> Invariants can be implicitly cast to const.
> 
> In my playing around with source code, using cstring's seems to work out 
> rather nicely.
> 
> So, why not alias cstring to invariant(char)[] ? That way strings really 
> would be immutable. The reason is that mutables cannot be implicitly 
> cast to invariant, meaning that there'd be a lot of casts in the code. 
> Casts are a sledgehammer, and a coding style that requires too many 
> casts is a bad coding style.

Perhaps I should just wait for the implementation, but I'm interested in 
knowing what your solution to .dup is. Given

    auto foo = "hello".dup;

what is the type of foo?

How do you support both of

    invariant char[] foo = "hello".dup;
    char[] bar = "hello".dup;

   -- Reiner



More information about the Digitalmars-d-announce mailing list