const issues and more!

Yigal Chripun yigal100 at gmail.com
Mon Jan 14 10:16:43 PST 2008


Michiel Helvensteijn wrote:
> Matti Niemenmaa wrote:
> 
>>>> How about:
>>>>
>>>> char[] text = "text".dup;
>>>>
>>>> .dup creates a mutable copy. There's also .idup, for an immutable copy,
>>>> but I don't know its semantics.
>>> You are of course correct, however it seems a tad unnecessarily verbose
>>> IMHO.
>> The advantage lies in optimization, as it's (more?) common to not want to
>> modify a string literal, but only to output it or a part of it. I don't
>> find it that verbose, but I don't think I've ever used it in code other
>> than such examples. :-P
> 
> But wouldn't the expected behavior be to implicitly duplicate the string
> literal? Or better yet, to never actually allocate memory for the string
> literal at all, but simply use it to set the initial value of the variable?
> 

you're quite right, and on some OSes (Linux) no memory is allocated (on 
the heap/stack) but rather the value is store in ROM.
however, char[] is an array which means you could have done the following:
char[] a = "abc";
a[1] = 'd';
which would segfault because you're changing something in ROM!
that's why the type of string literals is variant(char)[] or string for 
short, and the above behavior is disallowed.



More information about the Digitalmars-d mailing list