Why string alias is invariant ?

Sean Kelly sean at f4.ca
Wed Jan 30 15:42:21 PST 2008


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.


Sean



More information about the Digitalmars-d mailing list