Why string alias is invariant ?

Sergey Gromov snake.scaly at gmail.com
Wed Jan 30 17:09:38 PST 2008


Sean Kelly Wrote:
> Sergey Gromov wrote:
> > Really, why ?  You can't assign a dynamically created data to a variable of type string.  You can't pass a dynamically created data into a function receiving string !  If you wanted efficiency, if you wanted to guarantee that anybody receiving string can receive a char literal without duplication,---make it const then.  Invariant casts to const(char)[] implicitly, so as char[].  And even then, I'd prefer plain old char[] for string and foo(in string s) for a function that guarantees not to change it.
> 
> I think the hope is that 'string' will place us in a position to get
> functional programming-type optimizations "for free" once the language
> and compiler are in a position to provide them.  Such optimizations
> typically aren't possible with "const char[]" because the compiler must
> assume that the string data could change unexpectedly.  In essence, I
> believe that 'invariant' is intended for optimization while 'const' is
> intended for documenting/enforcing API contracts.

I don't quite get it.  If 'const' is "for documenting/enforcing API
contracts", then "string[] listdir(string)" is an API bug.  If it were
"char[][] listdir(in char[])", then the compiler wouldn't be able
to "get functional programming-type optimizations" within
the 'listdir()'.  Overall, the use of invariant 'string' is limited
to unmodified string literals and their substrings, because for
other data the behaviour is undefined, by specification.

SnakE



More information about the Digitalmars-d mailing list