how would D be different if string were const(char)[]?

Daniel Davidson nospam at spam.com
Thu Oct 17 12:17:37 PDT 2013


On Thursday, 17 October 2013 at 18:28:31 UTC, Meta wrote:
> On Thursday, 17 October 2013 at 13:08:18 UTC, Daniel Davidson 
> wrote:
>> If it would be no different then why prefer immutable(char)[] 
>> for string?
>
> Strings are immutable in quite a few other languages. Ex: Java, 
> Python. I found this old article written by Walter:
>
> http://www.drdobbs.com/architecture-and-design/invariant-strings/228700475

True and I believe they do it without an immutable keyword. I'm 
not questioning the value of a non-mutable type, just trying to 
get to the heart of why the keyword immutable is preferred over 
const in this example. Dicebot clarified it - essentially it is 
because sharing can creep in before it gets settled into a 
const(char)[] context. And once sharing has potentially happened 
you can't undo it except for transitive deep copy.

Had D gone with:

struct String {
    const(char)[] s_;
    this(char[] s) { s_ = s.dup; }
}

and not allowed any modification of elements you would still have 
immutable without the keyword. Granted, it would not be efficient 
so I see the benefit.

Strings/slices have sharing. Can the same issue/benefit occur 
with primitives? Would you ever have a need for `immutable(int)` 
over `const(int)`?


More information about the Digitalmars-d-learn mailing list