Why it doesn't compile in D 2.0?

Lutger lutger.blijdestijn at gmail.com
Sun Jan 17 03:54:31 PST 2010


On 01/17/2010 01:38 AM, Simen kjaeraas wrote:
> Lutger <lutger.blijdestijn at gmail.com> wrote:
>
>> Perhaps this is or should be a bug. You can override dup to work in ctfe:
>>
>> char[] dup(string str)
>> {
>> return str.dup;
>> }
>>
>> class Test {
>> string t1 = "test"; //Ok!
>> char[] t2 = "test".dup; //Compile error
>> char[] t3 = "test".dup(); //Ok!
>> }
>
> The problem with this approach is that you now have a pointer to mutable
> data, the contents of which are stored in the static data segment, and thus
> actually immutable.
>
> Second (and this is related to the first), the pointer will be the same for
> all instances, and thus changing the contents of one will change the
> contents of all.
>
> IOW, what one (probably) wants in this situation, is a constructor.
>


Thanks man, this is a big error of mine. Trying to manipulate the char[] 
does indeed do a segfault! I can't seem to find an explanation in the 
spec of how initializers are supposed to work, so I assumed incorrectly 
it would be ok.

I find it a bit disturbing that you can end up with a mutable reference 
to immutable data so easily, without casting or anything.


More information about the Digitalmars-d-learn mailing list