const issues and more!

Yigal Chripun yigal100 at gmail.com
Mon Jan 14 14:54:36 PST 2008


Michiel Helvensteijn wrote:
> Yigal Chripun wrote:
> 
>>> 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.
> 
> But wouldn't you want that to work exactly as written?
> 
> char[] str = "abc";
> a[1] = 'd';
> assert(str == "adc");
> 
> "abc" here is just the initial value of the mutable variable str. So it
> should be allocated in the memory pointed to by str.
> 
> In other words, an implicit cast should take place, or an implicit
> duplication should be made.
> 
> That it doesn't work like that is, in my opinion, a flaw of the language. D
> seems to continually get more difficult to use.
> 
to asnswer your question: no.
an important principle of D is COW (copy on write).
everywhere in D where you need a copy, you explicitly state that with a 
dup method or if you need to allocate memory for an object you use:
---
auto variable = new Type(params); // for example..
---
an implicit cast is a semantic error: the D spec says that an invariant 
cannot be cast implicitly to mutable, one of the reasons is because the 
compiler uses invariant to optimize code, another is the fact the 
invariant mean "nobody will change that object" and if you cast to 
mutable undefined behavior follows. meaning that a cast to mutable 
breaks the meaning of invariant.

an implicit duplication is also wrong: just read Steven's explanation in 
this thread.



More information about the Digitalmars-d mailing list